[英]Multiplying doubles in C++ error
我有一個看似簡單的C ++問題,困擾着我。 代碼的輸出
#include <iostream>
using namespace std;
int main() {
// your code goes here
double c = 9.43827 * 0.105952 ;
cout << c << endl ;
return 0;
}
是1.僅1.我猜想這是由於精度損失所致,該精度損失取決於c ++中double的存儲方式,但是c ++中肯定必須有一種方法可以在結果中獲得某種精度(小數點后2位或3位)。
這不是存儲中的精度損失,而是轉換為文本時的精度損失。 用於double的流插入器默認為六個有效數字。 乘積1.000003583,四舍五入為六個有效數字,為1.00000。 另外,如果尚未設置showpoint
,則尾隨零和小數點將被showpoint
,因此您將看到一個裸露的1。要顯示小數點,請使用std::cout << std::showpoint << c << '\\n';
。 要查看更多有效數字,請使用std::cout << std::setprecision(whatever) << c << '\\n';
, whatever
您希望格式化程序使用的位數是多少。
#include <stdio.h>
int main() {
// your code goes here
double c = ((double)9.43827) * 0.105952 ;
for(int i = (sizeof(double)*8)-1; i >= 0; i-- ) {
printf("%ld", (*(long*)&c>>i)&1);
}
}
如果運行該命令,則可以清楚地看到double的位表示不是整數值1。您不會丟失任何數據。
0011111111110000000000000000001111000001110100001010001001001001
但它非常接近1,因此才打印出來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.