因此設計問題是:查找用戶在C++中輸入的最大數字的平均值3
輸入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;
}
在使用它之前,您不會初始化num1,這會導致[* undefined behavior *](http://en.wikipedia.org/wiki/Undefined_behavior)。你也不會增加總和。 – 2014-09-12 19:11:56
我會改變它初始化num1謝謝我意識到我還沒有增加總和,但代碼是不完整的問題,我正在做它的碎片和測試它,並被卡在這部分.. – RJH 2014-09-12 19:37:01