[英]C++ Inaccurate Calculation
我在計算浮點數時得到了錯誤的答案。
float total =1;
for(int i= 0; i<16;i++){
total = total * floats_array[i];
if(i!=15)
cout << floats_array[i] << " * ";
else
cout << floats_array[i] << " = ";
}
cout << total << "\n";
我需要3位數的東西指向。
任何建議?
您是否嘗試打印最多三位小數?
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
vector< float > floats_array( 16, 1.123 );
float total = 1;
for(int i = 0; i<16;i++) {
total = total * floats_array[i];
}
float rounded_total = std::floor( total * 1000 ) / 1000;
cout << "total = " << total << endl;
cout << "total (rounded) = " << rounded_total << endl;
return 0;
}
其輸出為total = 6.398
(而不是total = 6.39847
)。
默認情況下,浮點值的格式最多為六位有效小數。 有操縱者可以改變這一點; 得到三個小數位,你想要的
#include <iomanip>
std::cout << std::fixed << std::setprecision(3) << total;
對我來說這打印362955.656
,你會注意到它仍然是不精確的:一個典型的32位float
只能給出六位或七位小數的精度。 使用double
可獲得更高的精度; 這給了我362955.533
,正確到至少三位小數。
從截圖中看,您打印的值看起來像是從float轉換為int,因為它正在向上舍入。 我會檢查你的陣列類型以及你的打印方式。 如果沒有更多代碼,就無法獲得更多細節。 提供更好的MVCE,以便從社區獲得更好的答案。
您可以嘗試使用類似的東西覆蓋cout
cout.precision(15);
cout << float_array[i];
cout << total;
這會將cout精度設置為15個位置。 您可以將此數字更改為您想要的任何數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.