Example(s):Palindrome, prime, armstrong, "linear search", reverse etc.
Example(s):1575, 1632, 1539 (Only one at a time)
Login
[lwa]
Solved Problem
#CPP#2331
Problem Statement - Average of three integer numbers, double output
Write a C++ program to find average of three integer numbers given by the user. The output can have fractional double precision values as well.
Solution
TC++ #2331
Run Output
Enter three integer numbers :12 37 13
Average of given numbers :20.6667
int a,b,c; cout<<“Enter three integer numbers :”; cin>>a>>b>>c;
Here we are collecting three integer values from the user in variables a, b and c. We are using a cin chain for collecting the input. Multiple values for cin chain can be given by giving space or tab between values or we also give them by pressing enter after the each value.
double avg=double (a+b+c)/3;
Here we take care that on the right hand side denominator should be first made a double precision variable before finding the average. If we do not do so only integer portion of the output may be retained. for example 5/2 in integer form would be 2 while in double(5)/2 form would be 2.5 .
cout<<“Average of given numbers :”<<avg<<endl;
Output is printed here.
Notes
The typecasting of numerator can be done in two forms. double (a+b+c) or as (double) (a+b+c) . When complex form of typecasting is done the first style is preferred, while for simple expressions the second style may be okay. Clarity of precedence is important. For e.g. if I write (double) a+b+c , one can have the impression that only a is typecasted.
Common Errors
Error in typecasting and precedence of operator has to be watched for. For e.g. watch for following expressions.(double) a+b+c/3 will give wrong result as it will first make division of 3 before adding to a+b. double ((a+b+c)/3) will also give wrong result in some cases as numerator calculation will first happen as integer and then division by integer will happen and then lastly double casting be done.