gpt4 book ai didi

c++ - 总和不会在此数组类型代码中正确打印出来

转载 作者:行者123 更新时间:2023-11-30 01:45:46 25 4
gpt4 key购买 nike

#include<iostream>
#include<fstream>

using namespace std;

int main()
{
ifstream inFile;
ofstream outFile;
int sum;
double average;
int apple[50];
int b1;
int i;

outFile.open("apple_trip.txt");

for (i = 0; i < 50; i++)
{
b1 = rand() % 100;
outFile << b1 << endl;
}

outFile.close();

inFile.open("apple_trip.txt");
for (i = 0; i < 50; i++) // This loop ensures you don't keep overwriting
// the same value, which would be off by 1
{
inFile >> apple[i];
}

for (i = 0; i < 50; i++) // The loop variable is i, not apple[i], and we stop at 50
{
if (apple[i] < 25)
{
cout << apple[i] << " people picked less than 25 apples" << endl;
}
}

for (i = 0; i < 50; i++)
{
if (apple[i] > 80 && apple[i] < 100) // change < to >
{
cout << "The number of apples that is between 80 and 100 is : " << apple[i] << endl;
}

}

for (i = 0; i < 50; i++)
{
sum = 0;
sum += apple[i];
average = sum / 50.0;
cout << average;
}
return 0;
}

基本上最后一个 for 循环不会正确打印出总和。它给出了一些奇怪的小数点。一直试图找出错误所在,但我只是 C++ 的初学者,而且我在计算机科学方面并不是很聪明。任何帮助将不胜感激!

最佳答案

for (i = 0; i < 50; i++)
{
sum = 0;
sum += apple[i];
average = sum / 50.0;
cout << average;
}

是的,这不会计算平均值。您必须在循环外初始化 sum 并打印 average

试试这个:

sum = 0;
for (i = 0; i < 50; i++)
{
sum += apple[i];
}
average = sum / 50.0;
cout << average;

average = sum/50.0; 可以在循环内部或外部,但在外部更好。

关于c++ - 总和不会在此数组类型代码中正确打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com