while循环是无限循环,第二次没有提示cin

时间:2017-09-30 15:06:43

标签: c++

我需要程序充当自动售货机,保持总计运行并确定变更(如果适用)。

#include <iostream>
using namespace std;

int main()
{

    cout << "A deep-fried twinkie costs $3.50" << endl;
    double change, n = 0, d = 0, q = 0, D = 0, rTotal = 0;

    do
    {
        cout << "Insert (n)ickel, (d)ime, (q)uarter, or (D)ollar: ";
        cin >> rTotal;
        if (rTotal == n)
            rTotal += 0.05;
        if (rTotal == d)
            rTotal += 0.10;
        if (rTotal == q)
            rTotal += 0.25;
        if (rTotal == D)
            rTotal += 1.00;

         cout << "You've inserted $" << rTotal << endl;


        cout.setf(ios::fixed);
        cout.precision(2);


        } while (rTotal <= 3.5);

        if (rTotal > 3.5)
            change = rTotal - 3.5;


            return 0;
}

1 个答案:

答案 0 :(得分:0)

你做错了几件事。首先,您需要有一个变量来读取选项的字符(n,d,q和D)。您还需要将这些字母用作字符(即'n'等)。然后,您需要将从输入中读取的选项与字符进行比较,而不是将插入的总数进行比较。最后,如果用户插入$ 3.50,则不需要再次迭代,因此条件应为rTotal < 3.5

以下是带有更正的代码:

#include <iostream>
using namespace std;

int main() {
    cout << "A deep-fried twinkie costs $3.50" << endl;
    double change, n = 0, d = 0, q = 0, D = 0, rTotal = 0;
    char op;
    do {
        cout << "Insert (n)ickel, (d)ime, (q)uarter, or (D)ollar: ";
        cin >> op;
        if (op == 'n')
            rTotal += 0.05;
        else if (op == 'd')
            rTotal += 0.10;
        else if (op == 'q')
            rTotal += 0.25;
        else if (op == 'D')
            rTotal += 1.00;
        cout.setf(ios::fixed);
        cout.precision(2);
        cout << "You've inserted $" << rTotal << endl;
    } while (rTotal < 3.5);
    if (rTotal > 3.5)
        change = rTotal - 3.5;
    return 0;
}

如果要计算用户插入的硬币,请将括号添加到if语句中,如果插入了这样的硬币,则将1添加到相应的变量中。