
Average in C++
#include <iostream>
using namespace std;
int main(void)
{
// Read the numbers.
cout << "Enter 3 numbers: ";
int n1, n2, n3;
cin >> n1 >> n2 >> n3;
// Compute the sum and average.
double sum = n1 + n2 + n3;
cout << "The mean of " << n1 << " " << n2 << " " << n3 << " "
<< "is " <<sum/3.0 << endl;
return 0;
}
C++ iostreams facility has a number of advantages over
C stdio.
- The type of conversion is determined by the type of variable.
- There are no %d constructs, so their
number cannot disagree with the number of arguments.
- There is no need to remember to use & on input.
Note that the stdio (printf, scanf and friends) still
exist. Generally, you will not want to use them in a new C++
program. They can be useful to avoid re-writing old programs
when adding C++ code, or for using C-based libraries which
do I/O.
Reading: Ch. 4; pp. 264-270