如果语句不起作用? [英] If statements not working?

查看:33
本文介绍了如果语句不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的菜鸟.我只是想问问下面的代码有什么问题:

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
", battlechoice);

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




");
        sleep(3000);
        break;
    }
}        //end fleeing

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

    damageoutcome = damagemax + damagemin;
}

发生的事情是它同时执行了两个 if 语句,即使它们都有不同的条件?怎么了?提前致谢.

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.

推荐答案

您将赋值运算符 = 与等号运算符 == 混淆了.改为写这个:

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

if (battlechoice == 4)

等等.

一些 C 程序员使用Yoda 条件"来避免在这些情况下意外使用赋值:

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)

这篇关于如果语句不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆