Assume a file named
Random.txt
exists, and contains a list of random numbers. Write a program that opens the file, reads all the numbers from the file, and calculates the following:
The program should display the number of numbers found in the file, the sum of the numbers, and the average of the numbers.
Output Labels:
Print each of the above quantities on a line by itself, preceded by the following (respective) strings: "
Number of numbers:
", "
Sum of the numbers:
", and "
Average of the numbers:
".
Sample Run
Number of numbers: 20
Sum of the numbers: 210
Average of the numbers: 10.5
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream reader("Random.txt");
int count=0;
int total=0;
int num;
if(!reader){
cout<<"cannot open the file\n";
return 0;
}
while(reader>>num){
count++;
total += num;
}
cout<<"Number of numbers in the file: "<<count<<std::endl;
cout<<"Sum of numbers: "<<total<<std::endl;
cout<<"Average of numbers: "<<1.0*total/count<<std::endl;
cout<<"======================================================\n";
reader.close();
return 0;
}
Comments
Leave a comment