Answer to Question #250458 in C++ for Ddg

Question #250458

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 number of numbers in the file
  • The sum of all the numbers in the file (a running total)
  • The average of all the numbers in the file


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 


1
Expert's answer
2021-10-13T00:29:30-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS