自从我使用C ++以来,已经有一段时间了,并决定尝试解决一个问题,以帮助我回忆旧材料。
基本上我要做的是创建一个小程序(使用Visual Studio): - 要求用户输入10个分数 - 计算最低,最高和平均分数。 - 显示所有10个分数,以及最低,最高和平均分数。
这是我写的代码:
#include <iostream>
using namespace std;
int main( )
{
int sum = 0;
int avg = 0;
int low = 0;
int high = 0;
int array[10];
cout << "Please enter 10 scores" << endl;
cout << " - - - - - - - - - - - " << endl;
for (int i = 0; i <= 10; i++)
{
cout << "Please enter a score: ";
cin >> i;
}
for (int i = 0; i <= 10; i++)
{
sum += array[i];
if (array[i] < array[i]+1)
{
low = array[i];
}
else if (array[i]+1 < array[i])
{
high = array[i];
}
else
low = array[i];
}
avg = sum/10;
for (int i = 0; i <= 10; i++)
{
cout << array[i] << endl;
}
cout << "The lowest score is: " << low << endl;
cout << "...and the highest score is: " << high << endl;
cout << "The average score is: " << avg << endl;
return 0;
}
我只想知道自己是否正常。我再一次尝试创建一个小程序: - 要求用户输入10个分数 - 计算最低,最高和平均分数。 - 显示所有10个分数,以及最低,最高和平均分数。
自从我使用C ++以来,已经有一段时间了,只是想知道我是否正在解决这个问题。非常感谢你。
答案 0 :(得分:0)
您的代码有些错误:
for(int i = 0; i < 10; i++)
array[i]
,而不仅仅是i
if (array[i] < array[i+1])
编辑后的总代码:
#include <iostream>
using namespace std;
int main( )
{
int sum = 0;
int avg = 0;
int low = 999999;
int high = 0;
int array[11];
cout << "Please enter 10 scores" << endl;
cout << " - - - - - - - - - - - " << endl;
for (int i = 0; i < 10; i++)
{
cout << "Please enter a score: ";
cin >> array[i];
//sum+=array[i];
}
for (int i = 0; i < 10; i++)
{
sum += array[i];
if (array[i] < low)
{
low = array[i];
}
if (array[i] > high)
{
high = array[i];
}
}
avg = sum/10;
for (int i = 0; i < 10; i++)
{
cout << array[i] << endl;
}
cout << "The lowest score is: " << low << endl;
cout << "...and the highest score is: " << high << endl;
cout << "The average score is: " << avg << endl;
return 0;
}
答案 1 :(得分:0)
简化方式
for (int i = 0; i < 10; i++)
{
cout << "Please enter score " << i+1 << " : ";
cin >> a[i];
}
high = low = a[0];
for (int i = 0; i < 10; i++)
{
cout << a[i] << endl;
sum += array[i];
if (array[i] < low)
low = array[i];
else if (array[i] > high)
high = array[i];
}