192k views
0 votes
Write a complete program, using proper standards, to open a file called "numbers". integer numbers separated by some white spaces. The program will display to the screen total of the numbers, and their average with 1 decimal digit, on two different lines. Make sure to read all numbers, and validate that the file was successfully opened and if not then display an error message and terminate the program.

User Arcturus
by
8.3k points

1 Answer

1 vote

Final answer:

To open a file called "numbers" and perform calculations, write a program in a programming language like Python. Read the file, split the numbers, calculate the total and average, and display them. Handle the file not found error.

Step-by-step explanation:

To open a file called "numbers" and perform calculations, you need to write a program in a programming language like Python. Here's an example:
try:
file = open('numbers', 'r')
numbers = file.read().split()
numbers = [int(num) for num in numbers]
total = sum(numbers)
average = round(total / len(numbers), 1)
print(f'Total: {total}')
print(f'Average: {average}')
except FileNotFoundError:
print('Error: File not found.')
finally:
file.close()

In this program, we open the file 'numbers' and read its contents. We split the numbers separated by white spaces and convert each number into an integer. Then, we calculate the total using the sum() function and the average by dividing the total by the number of numbers. The result is printed to the screen. If the file is not found, an error message is displayed.

User Quolonel Questions
by
7.5k points