vendredi 16 février 2018

C++ control loop output

I am reading from a file and need to do 2 things to it. This is the file:

January 3.2 February 1.2 March 2.2
August 2.3 September 2.4

I need to take the first 3 numbers and get their average then get the remaining 2 number's averages. My code outputs code but the way i wrote it it skips every other number.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream inputFile;
double number = 0, total = 0, average = 0, average2 = 0, total2 = 0;
int count = 0, counter = 0, counter2 = 0;
string name;
inputFile.open("Rainfall.txt");
if (inputFile)
{
    while (inputFile >> name >> number)
    {
        count++;
        if (count % 2)
        {

            total += number;
            counter++;
        }

        else
        {
            total2 += number;
            counter2++;
        }

    }
    average = total / counter;
    average2 = total2 / counter2;
    cout <<"March " << average << endl;
    cout << "September " << average2 << endl;
    inputFile.close();
}
else
{
    cout << "Error \n";
}
return 0;
}

I have thought about doing if (count < 4) but then that would be like hard coding it I thought.

Aucun commentaire:

Enregistrer un commentaire