0

I need help in reading a text file and by using a switch statement the user can either press 1 to find the average of all the integers in the text file, and by pressing 2 they find only the averages of the real numbers (only positive integers) in said file. I need help on the second part in computing the average for the real numbers only. This is my code thus far

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    int n;
    double average(0), sum(0), count(0);
    
    ifstream data;
    data.open("data.txt");  
    
    if(data.fail( ))
    { 
        cout << "Error Opening File"<<endl; 
        return 1;
    }
    

    
        while(!data.eof())
    {
        data>>n;
        sum=sum+n;
        count++;
    }

    int rank;
    cin >> rank;

    
    switch(rank){
                 
    case 1:
    average=(sum)/(count);
    cout << "The Average Is: " << average << endl;
    break;

}
    
    data.close();     
    
    cout << endl;
    system("PAUSE");
    return 0;

}
2
Contributors
1
Reply
5
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

Real numbers include both positive and negative numbers. Your use of the term "real numnbers" is misplaced.

You need another sum and count for all positive values. Then in the while statement add an if statement to sum up all values >= 0 (0 is also counted as a positive value).

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.