所以设计问题是:
输入3个数字并显示最大值。继续输入3个数字的集合,直到用户想要退出。找出所有最大数字的平均值。
所以输入数字工作正常但是当我尝试插入SENTINEL
值来停止循环时我需要为所有3个数字输入它并且它不能给我一个正确的过去的平均值输入数字。
非常感谢任何帮助,谢谢您的时间!
#include <iostream>
using namespace std;
int main()
{
const int SENTINEL = -1;
int num1;
int num2 = 0;
int num3 = 0;
int largest;
int sum;
int count;
float average;
// initialize the count and sum
count = 0;
sum = 0;
while (num1 != SENTINEL)
{
// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number ";
cin >> num1;
// Prompt the user for the second number
cout << "please enter second number ";
cin >> num2;
// Prompt the user for a third number
cout << "please enter the third number ";
cin >> num3;
// Compare numbers 1 and 2 for the largest number
if (num1 > num2)
{
largest = num1;
}
else
{
largest = num2;
}
// Compare largest to last number input
if (num3 > largest)
{
largest = num3;
}
// Display the largest number
cout << "largest number is: " << largest << endl;
// Increment the count
count++;
}
if (count > 0)
{
average = sum / count;
cout << "Average of the numbers is " << average;
}
return 0;
}
答案 0 :(得分:1)
使用break;
指令是可能的,但通常被认为是不优雅且难以维护。
原因是你打破了代码的流程,你的程序的读者(可能不是你在大程序中或者如果你共享它)期望循环的代码继续到它的结尾。如果你的函数有一个或多个break;
指令,可能很难理解函数的意图,因为你必须记住循环已经结束的情况。
解决问题的基本原则是在获取num1的值之后,在正确的位置开始循环。然后你的循环也必须以它结束。这样,您将始终在用户键入num1后立即检查退出条件。
// initialize the count and sum
count = 0;
sum = 0;
// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number ";
cin >> num1;
while (num1 != SENTINEL)
{
// Prompt the user for the second number
cout << "please enter second number ";
cin >> num2;
// Prompt the user for a third number
cout << "please enter the third number ";
cin >> num3;
// Compare numbers 1 and 2 for the largest number
if (num1 > num2)
{
largest = num1;
}
else
{
largest = num2;
}
// Compare largest to last number input
if (num3 > largest)
{
largest = num3;
}
// Display the largest number
cout << "largest number is: " << largest << endl;
// Increment the count
count++;
// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number ";
cin >> num1;
}
if (count > 0)
{
average = sum / count;
cout << "Average of the numbers is " << average;
}
return 0;
注意:我没有在这里解决代码错误,如注释中所述(变量未声明,总和未更新等)。
答案 1 :(得分:0)
输入num1后立即有条理地断开循环。
cin >> num1;
if (SENTINEL == num1)
{
break;
}
答案 2 :(得分:0)
在
cin >> num1;
你可以查看它的SENTIEL号码是否从循环中断:
if (num1 == SENTIEL)
break
这样它就不会执行另一个cin了。