2 answers
Best answer
#include <iostream>
using namespace std;
class Average {
private:
int num1, num2, num3;
float avg;
public:
// Constructor to accept three values
Average(int n1, int n2, int n3) {
num1 = n1;
num2 = n2;
num3 = n3;
}
// Function to calculate average
void calculateAverage() {
avg = (num1 + num2 + num3) / 3.0;
}
// Function to print average
void printAverage() {
cout << "The average of " << num1 << ", " << num2 << ", and " << num3 << " is: " << avg << endl;
}
};int main() {
// Create an instance of the "Average" class
Average myAverage(5, 10, 15);
// Calculate the average and print it
myAverage.calculateAverage();
myAverage.printAverage();
return 0;
}
In the constructor, the values of num1, num2, and num3 are initialized with the values passed as arguments. The calculateAverage function calculates the average of these three numbers and stores it in the avg member variable. The printAverage function prints out the values of num1, num2, num3, and avg. In the main function, an instance of the "Average" class is created with the values 5, 10, and 15. The average is then calculated and printed out.
Answer: The constructor below reads the three values from the user with cin; one member function calculates the average and another prints it.
#include <iostream>
using namespace std;
class average
{
float a, b, c, avg;
public:
average() // constructor
{
cout << "Enter three numbers: ";
cin >> a >> b >> c;
}
void calculate()
{
avg = (a + b + c) / 3;
}
void display()
{
cout << "Average = " << avg << endl;
}
};
int main()
{
average obj; // constructor runs and takes input
obj.calculate();
obj.display();
return 0;
}How it works:
- When the object
objis created, the constructoraverage()is called automatically and reads the three numbers from the keyboard. calculate()finds \((a+b+c)/3\) and stores it inavg. The variables arefloat, so the result is not truncated.display()prints the average.
Sample run: entering 4 5 9 prints Average = 6.
Your answer
Log in or create a free account to answer this question.