代码不会超出输入阶段

时间:2015-03-02 16:28:01

标签: c++

我构建了一个简单的程序,该程序应该以用美元和美分的形式输入并以美元和美分的形式输出美分,但是,当我运行它时,它会询问我的金额,我输入它,程序不会继续。我是编程新手,非常感谢我能帮助解决这个问题

 #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;
    }

4 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

这个while循环没有任何意义。删除它。

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

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

答案 2 :(得分:0)

你的&#39;你有一个无限循环。阻止,因为麻木总是积极的(任何迭代都不会改变) 尝试删除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;
}

您还可以查看其他答案,这些答案可让您使用循环来反复询问(有效)用户输入。

答案 3 :(得分:0)

你做了一个无限循环

while (numb>=0);
        {
          dollars=int(numb/100);
          cents=numb%100;
        }
麻木让我们说3,所以这总是3&gt; = 0等于真,因此,你就是那个循环