Finding Average Of Six Decimal Digits


Average

Starting with some basic general math concepts we will find out what our problem really is then we will move on to deriving a precise and handy solution. 

Average Formula:




Source Code

#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
 float num1, num2, num3, num4, num5, num6, avg, sum;
 cout << "Enter 1st number: ";
 cin >> num1;
 cout << "Enter 2nd number: ";
 cin >> num2;
 cout << "Enter 3rd number: ";
 cin >> num3;
 cout << "Enter 4th number: ";
 cin >> num4;
 cout << "Enter 5th number: ";
 cin >> num5;
 cout << "Enter 6th number: ";
 cin >> num6;
 sum = num1 + num2 + num3 + num4 + num5 + num6;
 avg = sum / 6.0;
 cout << endl << "Average: " << fixed << setprecision(0)
        << avg << endl;
 return 0;
}

Logic Explained:

Datatypes: As division results in decimal values in most cases so we have declared our variables with floating point datatype so that none of our result get disturbed and no part of it get truncated.
fixed: Fixed is part of iomanip header file, it is used to set floatfield to a fixed point notation which is specified by setprecision here we have used precision of 2 so it will show values upto 2 decimal points.

Output:

 

Alternate ways:

  1. One way is to make use of arrays to solve this problem. This will make our code small, more smarter and clean.
  2. The other way is to use loops with single variable and at each input from user overwriting it and summing it till loop condition matches.
As this program is for absolute beginner's we have restricted our code to the basics to make logic clear and easily understandable.
Note:
I will highly recommend you to try the alternate ways for your own practice it will be a good practice.
Join us at Facebook The Destined Programmer 
Subscribe our newsletter.
For any queries join our chat or comment below.

SHARE

About Hadi

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

Disqus