这是任务要求:您可以输入各种数字,但当您连续输入两次0时,它需要停止。在首次输入数字时,不允许输入0。
这是我设置的代码:
class MainClass
{
public static void Main (string[] args)
{
int givenNumber, prevNumber;
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
// I've set the prevNumber to givenNumber because the variable has to be initialized
// before I can use it in the condition below. I thought setting it to the giveNumber
// wouldn't harm. Note that the first time your not allowed to enter 0
prevNumber = givenNumber;
while (givenNumber != 0 && prevNumber != 0) {
prevNumber = givenNumber; //Here is where they both are 0 at a given moment, but only after the condition.
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
}
Console.WriteLine ("Tada");
}
}
问题在于当你只输入一个0时,程序就已经停止了。例如,如果我首先输入7,然后接下来输入0。当我调试它时,它会说我的给定数字是0,上一个数字是7,当它回到while条件时,它就停止并结束了。当程序完成时,调试清楚地显示prevNumber = 7和givenNumber = 0。我使用的条件AND是正确的,不是吗?
有什么线索吗?我不能使用数组来解决这个问题。
提前感谢您的帮助。
while ((givenNumber != 0) && (prevNumber != 0)) {
- RBarryYoung