簡體   English   中英

C ++字符串加倍atof轉換會失去精度?

[英]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);

函數atof創建一個double。 這里 您的問題是%g返回浮點數或科學計數形式中的較短者。 這里 另請注意,您正在添加in *表示表示預期的打印字符數截斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM