在循环处于无限循环时,请执行第二次cin

Do while loop is in infinite loop, doesnt prompt for cin second time through

本文关键字:执行 第二次 cin 循环 无限循环      更新时间:2023-10-16

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

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

您做错了几件事。首先,您需要具有一个变量来读取选项的字符(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添加到相应的变量中。