如果语句不工作?(If statements not working?)

2019-07-18 03:33发布

我在编程小白。 我只是想问问什么是错用下面的代码:

scanf("%i", &battlechoice);

printf("BCHOICE WAS:%i\n", battlechoice);

if (battlechoice=4) //fleeing
{
    fleechance=rand() % 100;
    if (fleechance <= 49)
    {
        printf("You attempt to flee...\n");
        sleep(2000);
        printf("Oh dear! You failed to flee! Gamover!\n");
        printf("Thank you for playing! -Anthony\n");
        sleep(7000);
        exit(0);
    } 
    else
    {
        printf("You succeeded in fleeing! You will be returned to town\nshortly...\n\n\n\n\n");
        sleep(3000);
        break;
    }
}        //end fleeing

else if (battlechoice=1) //attacking
{
    //player damage gen
    printf("You commence the attack...\n");
    sleep(750);
    damagemax = rand() % lvl * 1.4;

    damageoutcome = damagemax + damagemin;
}

正在发生的事情是,它是做两个if语句,尽管它们都具有不同的条件是什么? 怎么了? 提前致谢。

Answer 1:

你混淆了赋值运算符=与等于运算符== 。 而不是这样写:

if (battlechoice == 4)

等等。

一些C程序员使用“尤达条件句”,以避免无意中在这些情况下使用分配:

if (4 == battlechoice)

例如,这将不能编译,醒目的错误:

if (4 = battlechoice)


Answer 2:

你写如果(battlechoice = 4)如果纠正(battlechoice == 4)

因为“=”和“==”运营商两者都不同

“=”是赋值运算符和“==”是比较操作符

看到C的链路为运营商http://www.tutorialspoint.com/cplusplus/cpp_operators.htm



文章来源: If statements not working?