In: Computer Science
Write a C++ program that takes 4 readings of temperature, each reading is between -10 and 55. The program should: • Computes and print out the average temperature (avgTemp), maximum temperature (maxTemp) and minimum temperature (minTemp) of the day. • The program should also compute and print out the number of temperature readings (numTemp) that exceed 35. • Enforce validation on the user input (using while loop) and use appropriate format for the output. The average temperature should be rounded up the nearest digit.
without using arrays
Source code of the program is given below.Detailed comments are included for better understanding the code.Screen shot of the code and output are also attached.If find any difficulty, feel free to ask in comment section. Please do upvote the answer.Thank you.
Source code
#include<iostream>
//including cmath header file to use round() function
#include<cmath>
using namespace std;
int main()
{
//declaring variables to hold various values
//assigning maxTemp to minimum possible and minTemp to
maximum possible values
float
temp,avgTemp,maxTemp=-10,minTemp=55,total=0;
int numTemp=0,i;
//prompt user to enter 4 temperatures
cout<<"Enter four temperature(in between -10 and
55):"<<endl;
//initialize i with 1
i=1;
//loop executes its body as long as i is less than or
equals to 4
while(i<=4)
{
//prompt to enter temperature
i
cout<<"Enter temperature
"<<i<<": ";
//reading the temperature
cin>>temp;
//checking the temperature is
invalid
if(temp<-10||temp>55)
{
//if input is
invalid, print error message and force to do next iteration
//using continue
statement without updating i value to its next
cout<<"Invalid input!"<<endl;
continue;
}
//if user input is valid
else
{
//update total
by adding temp into it
total=total+temp;
//checking if
temp is greater than maxTemp
if(temp>maxTemp)
//if yes,set
temp as new maxTemp
maxTemp=temp;
//checking if
temp is less than minTemp
if(temp<minTemp)
//if yes,set temp as new minTemp
minTemp=temp;
//checking temp
greter than 35
if(temp>35)
//if yes,increment numTemp by 1
numTemp++;
//incrementing i
by 1
i++;
}
}
//calculating average
avgTemp=total/4;
//printing results
//avgTemp is rounded up to nearest digit using round()
function
cout<<"\nAverage Temperature:
"<<round(avgTemp)<<endl;
cout<<"Maximum Temperature:
"<<maxTemp<<endl;
cout<<"Minimum Temperature:
"<<minTemp<<endl;
cout<<"Number of temperature exceeding 35:
"<<numTemp;
return 0;
}
Screen shot of the
code
Screen shot of the output