177k views
0 votes
Write a program that calculates the average rainfall for three months. The program should ask the user to enter the name of each month, such as June or July, and the amount of rain (in inches) that fell each month. The program should display a message similar to the following: The average rainfall for June, July, and August is 6.72 inches.

2 Answers

2 votes

Here's a simple Python program that calculates the average rainfall for three months entered by the user:

The Code

# Function to calculate average rainfall

def average_rainfall():

total_rainfall = 0

months = ['first', 'second', 'third'] # To store month names

for i in range(3):

month_name = input(f"Enter the name of the {months[i]} month: ")

rainfall = float(input(f"Enter the amount of rain (in inches) that fell in {month_name}: "))

total_rainfall += rainfall

average = total_rainfall / 3

print(f"The average rainfall for the entered months is {average:.2f} inches.")

# Call the function to calculate average rainfall

average_rainfall()

This program prompts the user to enter the names of three months and their respective rainfall amounts. It calculates the total rainfall and then computes the average by dividing the total by 3. Finally, it displays the average rainfall for the entered months.

User Hilton Giesenow
by
5.9k points
4 votes

Answer:

// program in C++.

#include <bits/stdc++.h>

using namespace std;

// main function

int main()

{

// string array

string m[3];

// array to store rainfall

double rainfall[3];

// variables

double avg_rainfall,sum=0;

for(int i=0;i<3;i++)

{

cout<<"Enter name of month "<<i+1<<" :";

// read month name

cin>>m[i];

cout<<"Enter rainfall (inches) in month "<<i+1<<" :";

// read rainfall

cin>>rainfall[i];

// sum of rainfall

sum+=rainfall[i];

}

// Average rainfall

avg_rainfall=sum/3;

// print Average rainfall

cout<<"Average rainfall for "<<m[0]<<","<<m[1]<<","<<m[2]<<" is "<<avg_rainfall<<" inches."<<endl;

return 0;

}

Step-by-step explanation:

Create string array "m" to store name of month and double array "rainfall" to store rainfall. Read name of 3 months and rainfall in that month.Find the sum of all the rainfall and the average rainfall.Print the average rainfall of 3 months.

Output:

Enter rainfall (inches) in month 2 :45

Enter name of month 3 :july

Enter rainfall (inches) in month 3 :43

Average rainfall for may,june,july is 42.6667 inches.

User Dzhuneyt
by
6.1k points