To compute the average of an arbitrary number of temperatures read from standard input C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: To compute the average of an arbitrary number of temperature readings in C++ programming

To show: How to compute the average of an arbitrary number of temperature readings in C++ programming using arrays and pointers

 

// to compute the average of an arbitrary number of temperature readings

#include <iostream>

using namespace std;

 

void main(void)

{

float temper[40], sum = 0.0, *ptr;

int num, day = 0;

 

// set a pointer to an array

ptr = temper;

 

do

{

cout<<"Enter temperature for day "<<++day;

// prompt for input user input...

cout<<"\n(0-Terminate, Enter-Proceed): ";

// store in an array, pointed by ptr...

cin>>*ptr;

} while ((*ptr++) > 0);

 

// test if data entered is 0, then point to the next array position reset the pointer ptr to an array temper var

ptr = temper;

num = (day - 1);

// traverse the array temper

for(day = 0; day < num; day++)

// do the summing up

sum += *(ptr++);

// display the result...

cout<<"\nAverage temperature = "<<(sum/num)<<" Degree Celsius"<<endl;

cout<<"for "<<num<<" readings"<<endl;

}

 

Output example:

 

Enter temperature for day 1

(0-Terminate, Enter-Proceed): 34.5

Enter temperature for day 2

(0-Terminate, Enter-Proceed): 78.2

Enter temperature for day 3

(0-Terminate, Enter-Proceed): 56.4

Enter temperature for day 4

(0-Terminate, Enter-Proceed): 60.5

Enter temperature for day 5

(0-Terminate, Enter-Proceed): 56.6

Enter temperature for day 6

(0-Terminate, Enter-Proceed): 62.6

Enter temperature for day 7

(0-Terminate, Enter-Proceed): 58.7

Enter temperature for day 8

(0-Terminate, Enter-Proceed): 0

Average temperature = 58.2143 Degree Celsius

for 7 readings

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index