2016-09-27 58 views
-2

我写了这个程序的介绍,以补充科学课。它只是一个使用while循环的演示。我的教授将此程序标记为具有无限循环,但我不明白它是如何无限循环的,因为它在输入-1时终止。这是一个无限循环?

int main() { 

int accountNum, balance, totalOfItems, totalOfCredits, creditLimit; //Integers for the user to input 

while (accountNum != -1) 
{ 
    cout << "Enter account number" << endl; 
    cin >> accountNum; 
    cout << "Enter balance" << endl; 
    cin >> balance; 
    cout << "Enter total of all items charged this month" << endl; 
    cin >> totalOfItems; 
    cout << "Enter total of all credits applied to the account this month" << endl; 
    cin >> totalOfCredits; 
    cout << "Enter credit limit" << endl; 
    cin >> creditLimit; 

    int newBalance = balance + totalOfItems - totalOfCredits; 

    if (newBalance > creditLimit) 
    { 
     cout << "Account Number: " << accountNum << "\nCredit Limit: " << creditLimit << "\nNew Balance " << newBalance << endl; 
     cout << "Credit limit exceeded." << endl; 
    } else { 
     cout << "New balance : " << newBalance << endl; 
    } 
} 
return 0; 
} 
+4

你问过你的教授吗? – kfsone

+0

除非我错过了一些东西,否则我认为你是对的。该循环可以终止。 – Carcigenicate

+0

解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –

回答

6

显示的代码有多个错误。

  1. accountNum在使用之前未被初始化。这导致未定义的行为。

  2. 即使输入了-1,循环仍然会通过,并且仍然必须输入所有其余的输入。

  3. 如果输入无效输入,std::cin进入错误状态,并将永久循环。

1

显示的代码需要输入-1。如果输入流关闭或遇到错误(例如在其中一个数字中键入非数字值),则将永远不会收到-1的值。

除此之外,while循环条件仅在每次循环迭代开始时测试,它不是一个防护测试 - 因此输入一个-1的帐户仍然需要输入所有剩余值。

0

我认为这是因为在循环内从未满足-1的条件。

我看到的第一个条目:

cin >> accountNum; 

我会以为这是从来没有-1。

要结束循环,您需要将accountNum上的值存储为-1,以便接近循环代码的末尾。