當我獲得平均輸出的第一行時,它會顯示三個數字(即 v1、v2、v3),例如“30、54、99”,基本上沒有顯示點,但回圈中的下四行將顯示下一個像“44.00”這樣的三個亂數。
我正在嘗試像這樣獲得我的輸出
75 91 68 的平均值是: 78.00
85 76 93 的平均值為:84.67
67 21 11 的平均值是: 33.00
我的第一行出來了,但其他四個沒有。我嘗試使用 cin.clear 和 cin.ignore 清除緩沖區,但無濟于事。有任何想法嗎?
#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;
}
uj5u.com熱心網友回復:
該問題是你傳遞的引數功能average作為int替代的兩倍。該解決方案是只改變函式的引數average從int到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;
}
也將前向宣告更改為
double average(double num1, double num2, double num3);
此外,您可以使用static_cast<int>以您想要的形式獲取輸出。因此,將您的cout宣告更改為:
cout << "The average of "
<< static_cast<int>(v1) << " " << static_cast<int>(v2) << " " << static_cast<int>(v3)
<< " is: " << fixed << showpoint
<< setprecision(2) << avg
<< endl;
完整程式的輸出可以在這里看到,如下所示:
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
uj5u.com熱心網友回復:
只需將您的雙 v1 v2 v3 轉換為 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;
}
輸出
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345343.html
