If 语句和 post-增量作业:我没有得到我期望的结果 - 为什么?
If statement and post-increment homework: I'm not getting the result I'm expecting - why?
抱歉,如果这是一个愚蠢的初学者问题,但我完全被难住了。
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 statement"。对吗?
我错过了什么?
是的,是4
,让我们格式化代码(右缩进)看看:
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
除了单行条件,您需要使用大括号 { }
或者仅在条件为真时执行后的第一行代码。
/*
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
抱歉,如果这是一个愚蠢的初学者问题,但我完全被难住了。
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 statement"。对吗?
我错过了什么?
是的,是4
,让我们格式化代码(右缩进)看看:
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
除了单行条件,您需要使用大括号 { } 或者仅在条件为真时执行后的第一行代码。
/*
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