我应该允许用户输入非负数,一旦输入了负数,该功能应显示进行中的非负数的平均值。
我正在使用XCode进行C ++工作。
int Question6(){
double nums;
double totalnums = 0;
int count = 0;
cout << "Please enter the numbers that you like to be average that are non-negative:";
cin >> nums;
while (nums > 0){
cout << "Please enter the numbers that you like to be average that are non-negative:";
cin >> nums;
totalnums += nums;
count += 1;
if (nums < 0){
cout << "You have enterd a negative number so your average is:" << (totalnums/ count) << endl;
}
}
return 0;
}
我获得了成功的构建,但是它总是给我一个包含负数的平均值。有办法阻止这种情况发生吗?
答案 0 :(得分:4)
问题在这里:
int menu(std::vector <std::string> options) //menu creation
{
int input; //user selection
bool check = false; //check for valid input
.
.
.
while(!check)
{
std::cin >> input;
if(std::cin.fail() || input <= 0 || input > static_cast<int>(options.size()))
{
std::cin.clear();
std::cin.ignore();
std::cout << wrongInput << std::endl;
}
else
{
check = true; //change flag for valid input
}
}
return input;
}
问题是 while (nums > 0)
{
cout << "Please enter the numbers that you like to be average that are non-negative:";
cin >> nums;
totalnums += nums;
count += 1;
if (nums < 0)
{
cout << "You have enterd a negative number so your average is:" << (totalnums/ count) << endl;
}
}
循环中的if
指令。如果输入负数,它将被添加到while
指令中,因为它是totalnums+=nums
之后的下一条指令。之后,cin
条件变为while
,程序退出循环。
要解决您的错误,请检查false
之前,然后进入nums<0
循环。
答案 1 :(得分:1)
更干净的解决方案-具有错误检查 的-在有效输入时循环播放,然后根据输入的符号决定要执行的操作:>
while (std::cin >> number)
{
if (number >= 0)
{
// update values needed for average calculation
}
else
{
// calculate average, display
break; // exit the while loop
}
}
// Optionally: Check if loop exited due to read error or negative number
if (std::cin)
{
// read a negative value
}
else
{
// IO error (such as eof, no more numbers)
}