2015-03-02 40 views
0

我已经构造是应该采取美分的量的简单的程序,在美元和美分的形式,然而,当我运行它,它的用户输入,并将其输出向我询问金额,我输入它,程序不继续。我是新来的节目,并会深深地感谢所有帮助我能得到对此事代码不进行超出输入级

#include <iostream> 

    using namespace std; 

    int main() 
    { 
     int numb; 
     int dollars=0; 
     int cents=0; 

     cout << "Enter the amount" << endl; 
     cin >> numb; 

     while (numb>=0); 
     { 
      dollars=int(numb/100); 
      cents=numb%100; 
     } 

     cout << dollars << "dollars" << cents << "cents"<<endl; 

     return 0; 
    } 
+2

:为什么使用while循环吗? – Sumeet 2015-03-02 16:29:14

+2

尝试使用调试器,找到错误你自己 – Imran 2015-03-02 16:32:12

回答

0

你必须与你“而”块,因为麻木始终为正(它不会为任何改变一个无限循环迭代)。
尝试删除while循环以让程序继续。

#include <iostream> 

using namespace std; 

int main() 
{ 
    int numb; 
    int dollars=0; 
    int cents=0; 

    cout << "Enter the amount" << endl; 
    cin >> numb; 

    dollars=int(numb/100); 
    cents=numb%100; 

    cout << dollars << "dollars" << cents << "cents" << endl; 

    return 0; 
} 

您还可以看看其他答案,这些答案为您提供了使用循环重复询问(有效)用户输入的方法。

+0

我敢肯定while循环是有处理无效输入(即负值),所以它不是一个真正的好主意,告诉他没有至少告诉他将其删除原因。此外,此代码也不处理非数字数字。 – 2015-03-03 08:01:00

+0

的确,我应该解释为什么。我已经在这方面编辑了我的答案。就问题而言,OP正试图让程序继续下去;我认为你的回答对他简单的程序来说是一个很好的后续。 – birdypme 2015-03-04 08:43:13

1

这while循环没有任何意义。去掉它。

while (numb>=0); // remove this line and the '{' '}' 
{ 
    dollars=int(numb/100); 
    cents=numb%100; 
} 

通常在使用循环时检查它们是否会终止。您正在检查每个迭代numb>=0,但在循环内numb永远不会改变它的值。所以程序永远执行这个循环。

0

你做一个无限循环

while (numb>=0); 
     { 
      dollars=int(numb/100); 
      cents=numb%100; 
     } 

麻木是让我们说3,所以这总是3> = 0等于true,因此,您neverexit这个循环

+0

你做了疯狂的缩进。怎么来的? – 2015-03-02 16:46:22

2

的代码如你预期下面应该工作。 阅读我插入代码中的注释以获取更多信息。 此外,您可能要插入的循环合法输入额外的检查(即非数字字符)因为这将导致循环进入无限循环。

编辑:我已经用额外的检查处理无效的非数字用户输入更新的代码。

#include <iostream> 
using namespace std; 

int main() 
{ 
    int numb = 0; 
    int dollars=0; 
    int cents=0; 

    cout << "Enter the amount" << endl; 

    // I suspect your while loop here is to keep soliciting input 
    // if the input is not valid, so I've moved the "cin" into the loop. 
    // Don't use semi colon here after the while statement because 
    // in doing so, you're eliminating the body of the loop. 
    while (numb <= 0) 
    { 
     cin >> numb; 
     if(cin.fail()) { 
      cin.clear(); 
      cin.ignore(numeric_limits<int>::max(), '\n'); 
      cout << "Non numeric input, please try again." << endl; 
      continue; 
     } 
     cout << "numb: " << numb << endl; 
     dollars=int(numb/100); 
     cents=numb%100; 
    } 

    // I've inserted extra spaces around dollars and cents here 
    // to make the output more readable. 
    cout << dollars << " dollars " << cents << " cents"<<endl; 

    return 0; 
}