Average of 3 Numbers in C++
Average of 3 Numbers in C++ (4 Programs).
1#include <iostream>2#include <iomanip>3using namespace std;45int main() {6 float num1, num2, num3;78 cout << "Enter three numbers: ";9 cin >> num1 >> num2 >> num3;1011 float average = (num1 + num2 + num3) / 3.0;1213 cout << fixed << setprecision(2);14 cout << "Average of " << num1 << ", " << num2 << ", and " << num315 << " = " << average << endl;1617 return 0;18}
Output
Enter three numbers: 10 20 30 Average of 10.00, 20.00, and 30.00 = 20.00
What's going on
The program calculates the average of three numbers. For example:
The average represents the central value of a set of numbers, providing a single value that summarizes the data.
Example:
Header Files Used
Declaring Variables
The program declares:
float num1, num2, num3;
Taking Input From the User
The program asks:
cin >> num1 >> num2 >> num3;
The user enters three numbers, for example: 10 20 30
The >> operator can chain multiple inputs, reading them sequentially.
1cout << "Enter three numbers: ";
Calculating the Average
The calculation is done using:
float average = (num1 + num2 + num3) / 3.0;
How it works
:
Why 3.0 instead of 3?
:
Formatting the Output
To display the result with 2 decimal places:
1cout << fixed << setprecision(2);
Displaying the Result
The program prints:
<< " = " << average << endl;
Output:
Average of 10.00, 20.00, and 30.00 = 20.00
This clearly shows the input numbers and the calculated average.
1cout << "Average of " << num1 << ", " << num2 << ", and " << num3
Understanding the Average Formula
Mathematical Definition
:
Average = (Sum of all numbers) / (Count of numbers)
For three numbers:
Average = (a + b + c) / 3
Properties
:
Example Calculation
:
Numbers: 10, 20, 30
Other Methods (Mentioned but not shown in code)
Method 2: Using Functions
float calculateAverage(float a, float b, float c) {
}
1return (a + b + c) / 3.0;
Method 3: Using Arrays
float numbers[3];
float sum = 0;
for (int i = 0; i < 3; i++) {
cin >> numbers[i];
sum += numbers[i];
}
float average = sum / 3.0;
Method 4: Using Templates
template<typename T>
T average(T a, T b, T c) {
}
1return (a + b + c) / 3.0;
When to Use Each Method
-
Basic Formula
: Best for learning - simple and straightforward.
-
Functions
: Best for code organization - reusable and modular.
-
Arrays
: Good for handling many numbers - scalable approach.
-
Templates
: Best for generic code - works with different types.
Best Practice
: Use the basic formula for simple cases, or functions for better code organization.
Important Considerations
Data Type Selection
:
Division by Zero
:
Precision
:
Common Use Cases
Statistics
:
Programming Practice
: