If statements not working?

ⅰ亾dé卋堺 提交于 2020-01-18 05:45:49

问题


I am a noob at programming. I just wanted to ask what is wrong with the following code:

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;
}

What is happening is that it is doing both of the if statements, even though they both have different conditions? What is wrong? Thanks in advance.


回答1:


You're confusing the assignment operator = with the equals operator ==. Write this instead:

if (battlechoice == 4)

And so on.

Some C programmers use "Yoda conditionals" to avoid accidentally using assignment in these cases:

if (4 == battlechoice)

For example this won't compile, catching the mistake:

if (4 = battlechoice)



回答2:


you are writing if(battlechoice=4) correct it with if(battlechoice==4)

because '=' and '==' operators both are different

'=' is Assignment Operator and '==' is comparison operator

see the link for operators in C http://www.tutorialspoint.com/cplusplus/cpp_operators.htm



来源:https://stackoverflow.com/questions/14289635/if-statements-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!