When I get my first line of output for the average it shows the three numbers (ie. v1, v2, v3) like this "30, 54, 99" basically with no showpoint but the next four lines in the loop will show the next three random numbers like this "44.00".
I'm trying to get my output like this
The average of 75 91 68 is: 78.00
The average of 85 76 93 is: 84.67
The average of 67 21 11 is: 33.00
My first line comes out but the other four do not. I try clearing the buffer with cin.clear and cin.ignore but to no avail. Any ideas?
#include <iostream>
#include <cmath>
#include <iomanip>
#include <limits>
using namespace std;
double average(int num1, int num2, int num3);
int main() {
for (int i = 1; i <= 5; i ) {
double v1 = rand() % 100 1;
double v2 = rand() % 100 1;
double v3 = rand() % 100 1;
double avg = average(v1, v2, v3);
cout << "The average of "
<< v1 << " " << v2 << " " << v3
<< " is: " << fixed << showpoint
<< setprecision(2) << avg
<< endl;
}
return 0;
}
/// for loop to find the average
double average(int num1, int num2, int num3)
{
double avg = (num1 num2 num3) / 3;
return avg;
}
CodePudding user response:
The problem is you're passing the argument to function average
as int
instead of double. The solution would be to just change the parameters of function average
from int
to double
:
//note the parameters are changed to double instead of int
double average(double num1, double num2, double num3)
{
double avg = (num1 num2 num3) / 3;
return avg;
}
Also do change the forward declaration also to
double average(double num1, double num2, double num3);
Also, you can use static_cast<int>
to get the output in your desired form. So change your cout
statement to:
cout << "The average of "
<< static_cast<int>(v1) << " " << static_cast<int>(v2) << " " << static_cast<int>(v3)
<< " is: " << fixed << showpoint
<< setprecision(2) << avg
<< endl;
The output of the complete program can be seen here which looks like:
The average of 84 87 78 is: 83.00
The average of 16 94 36 is: 48.67
The average of 87 93 50 is: 76.67
The average of 22 63 28 is: 37.67
The average of 91 60 64 is: 71.67
CodePudding user response:
just convert your double v1 v2 v3 to int
#include <iostream>
#include <cmath>
#include <iomanip>
#include <limits>
using namespace std;
double average(int num1, int num2, int num3);
int main() {
for (int i = 1; i <= 5; i ) {
double v1 = rand() % 100 1;
double v2 = rand() % 100 1;
double v3 = rand() % 100 1;
double avg = average(v1, v2, v3);
cout << "The average of "
<< (int)v1 << " " << (int)v2 << " " << (int)v3
<< " is: " << fixed << showpoint
<< setprecision(2) << avg
<< endl;
}
return 0;
}
/// for loop to find the average
double average(int num1, int num2, int num3)
{
double avg = (num1 num2 num3) / 3;
return avg;
}
OUTPUT
The average of 42 68 35 is: 48.00
The average of 1 70 25 is: 32.00
The average of 79 59 63 is: 67.00
The average of 65 6 46 is: 39.00
The average of 82 28 62 is: 57.00