在循环处于无限循环时,请执行第二次cin
Do while loop is in infinite loop, doesnt prompt for cin second time through
我需要该程序充当自动售货机,继续运行总计并确定更改(如果适用)。
#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添加到相应的变量中。
相关文章:
- 如何从给定字符串中删除第二次和第三次出现的$
- getopt_long_only第二次调用时返回 -1
- 读取文件在第二次调用时返回INVALID_HANDLE
- 为什么我的信号处理程序只执行一次?
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 解释为什么第二次分配会改变性能
- 当再次触发信号时,从Qt插槽执行的功能被第二次调用时会发生什么?
- For循环在cpp中仅执行一次
- 在可变函数调用中执行一次语句
- 如何防止GUI挂起,同时允许第二次操作与Qt中的第一次操作一起执行
- 如何找到数组中值倒数第二次出现的索引
- arm_data在第二次运行我的程序时中止失败,然后
- Java 套接字读取在第二次读取时返回奇怪字符
- (QT) QThread 不执行第二次
- 在循环处于无限循环时,请执行第二次cin
- 在我的switch语句完全执行之前,我的while循环进入第二次迭代,我用c ++编码
- 从第二次调用开始在函数中执行一段代码
- EntityMap::iterator.第二次执行