我一直在无限循环?我需要改变什么来解决这个问题?我是初学者。请帮忙。我无法弄清楚这一点。我试着玩弄所有其他循环但仍然遇到同样的错误。
#include <iostream>
using namespace std;
int inputData();
int convertData();
int outputData();
int main ()
{
inputData();
return 0;
}
int inputData ()
{
int hours, minutes;
char am_pm;
cout << "Please enter hours: "; // ask user to input hours.
cin >> hours;
do
{
if (hours > 23)
{
cout << "ERROR! Must be less than 23" << endl;
}
}
while (hours > 23); // end of hours loop
cout << "Please enter minutes: ";
cin >> minutes;
do
{
if (minutes > 59)
{
cout << "Must be less than 59. Try again!" << endl;
}
}
while (minutes > 59);
}
答案 0 :(得分:2)
缩进可以挽救你的生命。
---> do {
| if (hours > 23) {
| cout << "ERROR! Must be less than 23" << endl;
| }
--- } while (hours > 23); // end of hours loop
例如,您的第一个周期(即使是第二个周期)检查的条件总是相同,但不会修改程序的状态,那么您认为它会如何改变终止条件?
应该是(非常小):
do {
std::cin >> hours;
if (hours > 23) {
std::cout << "Error\n";
}
} while (hours > 23);
答案 1 :(得分:0)
您需要移动hour prompting statements
即。 cout << "Please enter hours: "; // ask user to input hours.
cin >> hours;
到循环的do block
。
do {
cout << "Please enter hours: "; // ask user to input hours.
cin >> hours;
if (hours > 23)
{
cout << "ERROR! Must be less than 23" << endl;
}
} while (hours > 23); // end of hours loop
因此,如果用户输入无效小时,他将被重新提示,直到他进入有效小时。