总和不会在此数组类型代码中正确打印 [英] The sum wont print out correctly in this array type code

查看:108
本文介绍了总和不会在此数组类型代码中正确打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

basically the last for loop wont print out the sum correctly. It gives some weird decimals thingy. Been trying to see wheres the error but im just a beginner in c++ and im not really smart in computer science. Any help will be appreciated!

推荐答案

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

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

Yes, this won't calculate the average. You will have to initialize sum and print average outside the loop.

尝试:

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

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

average = sum / 50.0; can be either inside or outside of the loop, but outside is better.

这篇关于总和不会在此数组类型代码中正确打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆