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

时间:2015-12-02 00:44:50

标签: c++

#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 ++的初学者,我不是真正聪明的计算机科学。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

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;可以在循环内部或外部,但外部更好。

答案 1 :(得分:1)

如果我理解正确的话,你想要用最后一个循环做的是打印每次旅行的苹果的平均值,对于所有50次旅行。

如果是这种情况,它现在不能正常工作的原因是因为你在循环开始时将总和设置为0,并在结束时打印出平均值。你想要做的是从循环中初始化sum,并为平均计算和打印指令做同样的事情。这看起来像这样:

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

此时,您可以将其简化为大看起来像这样:

sum = 0;
for (i = 0; i < 50; i++)
    sum += apple[i];

average = sum / 50.0;
cout << average;

希望有所帮助! (如果那是你想要达到的目的; D)

答案 2 :(得分:0)

正如迈克所说,在循环之上整合和,并计算循环外的平均值。循环中唯一的东西应该是添加。

我想补充的一点是,你最好不要使用向量而不是原始数组。所以而不是:

int apple[50];
// ...
for (int i = 0; i < 50; i++)
{
    inFile >> apple[i];
}

我想你可能会这样做:

vector<int> apple;
int temp;
// ...
for (int i = 0; i < 50; i++)
{
    inFile >> temp;
    apple.push_back(temp);
}