尝试获得一些C ++基础但有问题。我需要获得温度数组值的平均值。在这里发布代码。我知道我做错了什么,因为我得错了答案。你能告诉我出了什么问题吗?
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, Temperature[100];
// -----------------------------------------
cin >> d;
for (i = 1; i <= d; i++)
{
cin >> Temperature[i];
}
for (i = 1; i <= d; i++)
{
cout << Temperature[i] << endl; // was Temperatura[i] ?
}
for (i = 1; i <= d; i++);
{
sum += Temperature[i];
}
avg= sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
system("pause");
return 0;
}
答案 0 :(得分:3)
问题是愚蠢错误的结果: -
for (i = 1; i <= d; i++); << semicolon
从for循环结束中删除分号。
答案 1 :(得分:0)
也许是因为输入数d大于100
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, *Temperature=0;
// -----------------------------------------
cin >> d;
Temperature=new double[d]; //<== Use new to allocate array
for (i = 0; i < d; i++) //<== Normaly array start at 0
{
cin >> Temperature[i];
}
for (i = 0; i < d; i++)
{
cout << Temperatura[i] <<endl;
}
for (i = 0; i < d; i++);
{
sum += Temperature[i];
}
average = sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
if(Temperature!=0) //<== Free memory
{
delete []Temperature;
}
system("pause");
return 0;
}
答案 2 :(得分:0)
int d;
作为输入之前,则不需要初始化d
。d
作为输入。现在宣布int Temperature[d];
,以便如果观察总数超过100,则应该有效。d-1
。for()
循环最后没有;
。答案 3 :(得分:0)
步骤: