|
After
this we will add all the ages to get the total age and store this total age
in a variable. Then we will get the average age of the ten students by
dividing this total age by 10. For the storage of total and average ages we
need variables. For this purpose we use variable TotalAge for the total of ages
and AverageAge
for average of ages respectively.
int TotalAge, AverageAge;
We
have declared AverageAge as int data type so it can
store only whole numbers. The average age of the class can be in real numbers
with decimal point (for example if total age is 173 then average age will be
17.3). But the division of integers will produce integer result only and the
decimal portion is truncated. If we need the actual result then we should use
real numbers (float or double) in our program.
Now
we have declared variables for storing different values. In the next step we prompt
the user to enter the age of first student. We simply show a text line on the
screen by using the statement:
cout << “Please enter the age of
first student : “;
So
on the screen the sentence “Please enter the age of first student:” will
appear. Whenever we are requesting user to enter some information we need to
be very clear i.e. write such sentences that are self explanatory and user
understands them thoroughly and correctly. Now with the above sentence
everyone can understand that age would be entered for the first student. As
we are expecting only whole numbers i.e. age in years only i.e. 10, 12 etc,
our program is not to expect ages as 13.5 or 12.3 or 12 years and 3 months
etc. We can refine our sentence such, that the user understands precisely
that the age would be entered in whole number only.
After
this we allow the user to enter the age. To, get the age, entered by the user
into a variable, we use the statement:
cin >> age1;
|