在C ++中,您可以将赋值作为条件进行评估,如下所示:In C++ what causes an assignment to evaluate as true or false when used in a control structure?
我在C#中尝试了相同的操作,但似乎不起作用。
public class Solution {
static int _x = 0;
public static bool DoStuff() {
if (_x > 10) {
return false;
} else {
++_x;
return true;
}
}
public static void Main(string[] args) {
bool didStuff = false;
while (didStuff = DoStuff()) {
Console.WriteLine("You shouldn't see this more than 10 times...");
}
if( didStuff) {
Console.WriteLine("Girl, you know it's true.");
}
}
}
输出:
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
You shouldn't see this more than 10 times...
我希望在控制台窗口的最后一行看到“女孩,你知道这是真的。”
while的计算结果为true,但是赋值有误。谁能解释为什么我看不到控制台的最终输出?
答案 0 :(得分:1)
只要while
是didStuff
,您的true
循环就会继续运行,一旦循环结束,就意味着didStuff
是false
。这就是为什么if
条件不满足且您期望的文本未写入控制台的原因。