In: Computer Science
Write C++ void function called averageTemperature() that asks the user to enter integers with a sentinel value of -999 to stop entering numbers. Then average the numbers and print the average.
You will need an int acculumator for the temperatures and an int acculumator for the number of temperatures entered. Use the accumulators to calculate the average which will need to be a decimal number.
Call the function from the main() function.
Answer:
#include<iostream>
using namespace std;
void averageTemperature() // function definition starts
here
{
float avg; // variable
declaration
int num,sum=0,count=0; /* 'count' is the
int accumulator for number of temperatures, 'num' is the int
accumulator for storing temperature*/
cout<<"Enter temperatures to calculate the
average (enter -999 to stop):";
while(cin>>num) // reading the
integer input from the keyboard and storing in
'num'
{
if(num!=-999) // if
'num' is not -999
{
sum += num;
// performs the sum
count++;
// increments the count of the
temperatures
}
else // if 'num' is
-999
break;
// jumps out of while loop
}
avg = (float)sum/count; // calculating the
average of temperatures
cout<<"The average temperature
is:"<<avg; // displaying the average
temperature
}
int main()
{
averageTemperature(); // function
call
return 0;
}
Output: