Assume that a file containing a series of integers is named numbers.txt. Write a program that calculates the average of all the numbers stored in the file. The input file may have numbers all on one line or several lines or one number on each line.

Respuesta :

Answer:

Program in Python:

file = open("numbers.txt", "r")

count = 0

isum = 0

content = file.readlines()

for nums in content:

    num = nums.rstrip('\n').split(" ")

         for i in num:

              isum= isum + int(i)

              count = count + 1

print("Average: "+str(isum/count))

Explanation:

This line opens the file named numbers.txt

file = open("numbers.txt", "r")

This line initializes num to 0

count = 0

This line initializes sum to 0

isum = 0

This line reads the content of the opened file file

content = file.readlines()

This iterates through the content of the file

for nums in content:

This removes trailing new lines and blank spaces from each number

    num = nums.rstrip('\n').split(" ")

This also iterates through the content of the file

         for i in num:

This calculates the sum of the numbers in the file

              isum= isum + int(i)

This counts the numbers in the file

              count = count + 1

This calculates and prints the average of the numbers

print("Average: "+str(isum/count))

fichoh

The program reads in a series of integer values from a text file and calculates the average of the values. The program is written in python 3 thus ;

with open("numbers.txt", 'r') as file :

#opens the file in read mode

content = file.readlines()

#reads in the contents of the file at once into a list

count = 0

#initialize counter

sum = 0

#initialize the sum of the integers

for line in content:

#loop through each line in the content list

num = line.rstrip("\n").split()

#removes the newline and splits the values based on whitespace

for val in num :

#loops through the list

count+=1

#increase count by one for every iteration

sum+=int(val)

#takes the Cummulative sum

print("average =", int(sum/count))

Learn more : https://brainly.com/question/20308959

ACCESS MORE