如果陈述和增加后的作业:我没有得到预期的结果-为什么?

时间:2019-08-09 14:30:30

标签: c# if-statement increment

很抱歉,如果这是一个愚蠢的初学者问题,但我完全感到困惑。

int i = 0;

if (i == 0)
    i++;
    i++;
if (i == 3)
    i += 2;
    i += 2;

Console.WriteLine(i);

好的,我的逻辑是,所以如果i = 0,请添加1,然后再添加1。所以最后i = 2

除了不是,它会打印出4

可能发生的唯一方法是通过第二个“ if语句”。对吧?

我想念什么?

2 个答案:

答案 0 :(得分:4)

是的,它是4,让我们格式化代码(输入正确的 indents ),然后查看:

int i = 0;   // i == 0

if (i == 0)  // i == 0
    i++;     // i == 1

i++;         // i == 2

if (i == 3)  // i == 2
    i += 2;  // doesn't enter (since i != 3)

i += 2;      // i == 4

答案 1 :(得分:1)

除了大写一行以外,您还需要使用大括号{} 或仅在条件为true时才执行之后的第一行代码。

/*
for example would be 

if (i == 0) 
{
    i++; 
    i++; 
}
*/

int i = 0;

//this is true
if (i == 0)
    i++; // so only this line gets executed i = 1
    i++; // this will get executed no matter what. i = 2
//at this point i = 2 so the conditional is false
if (i == 3)
    i += 2; // this line doesn't get executed
    i += 2; /* this is not in curly brackets { } so it will get executed no matter what the conditional returns as .. so i = 4*/

//i = 4
Console.WriteLine(i);
//and that's what prints

检查一下 https://www.learncs.org/en/Conditionals