C++字符串加倍转换失败精度?

sap*_*tos 5 c++

C++不是我的语言所以请原谅这个简单的问题.我在从字符串转换为双倍的转换中失去了精确度,任何人都可以帮忙吗?

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
Run Code Online (Sandbox Code Playgroud)

我在memset函数中使用%f但是这给出了131663.510000

提前致谢.

Sapatos

Rap*_*ien 3

问题是您的%g格式运算符没有指定足够的精度。您可能需要%.2f改为打印小数点后两位数字。