[英]C++ String to double atof conversion losing precision?
C ++不是我的語言,所以請原諒這個簡單的問題。 我在從字符串到雙精度的atof轉換中失去了精度,有人可以幫忙嗎?
string lAmount;
string lSuspendedInt = "131663.51";
string lAccruedInterest = "0.0";
double dSuspendedInt= atof(lSuspendedInt.c_str()); //PROBLEM HERE?
double dAccruedInterest = atof(lAccruedInterest.c_str());
double dTotal = dSuspendedInt + dAccruedInterest;
char cAmount[50];
memset(cAmount,0X00,sizeof(cAmount));
sprintf(cAmount,"%g*",dTotal);
lAmount = cAmount;
cout << "lAmount: "<<lAmount<<endl; //PRINTING: 131664 not 131663.51
我在memset函數中玩過%f,但這給出了131663.510000
提前致謝。
薩帕托斯
問題是您的%g
格式運算符,沒有指定足夠的精度。 您可能需要%.2f
,它在小數點后輸出兩位數。
sprintf
%g
格式說明符默認為打印六個有效數字。 如果需要更多,可以顯式指定應打印的數量:
sprintf(cAmount,"%.8g*",dTotal);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.