将字符串转换为双精度会四舍五入为整数
Converting string to double keeps rounding to the whole number
我正在尝试将 string
十进制数转换为 double
,但是当我使用 atof()
函数时,我的数字最终四舍五入为整数。
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string num = "135427.7000";
double r = atof(num.c_str());
cout << r << endl;
}
输出为:
135428
我要:
135427.7
cout
这样做,而不是 atof()
。
更准确地说,operator<<
,它将格式化数据插入 std::ostream
。
您可以使用 std::setprecision()
from the <iomanip>
标准库来打印小数:
cout << setprecision(7) << r << endl;
或
cout << fixed << setprecision(1) << r << endl;
如果要打印整个135427.7000
:
cout << fixed << setprecision(4) << r << endl;
我正在尝试将 string
十进制数转换为 double
,但是当我使用 atof()
函数时,我的数字最终四舍五入为整数。
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string num = "135427.7000";
double r = atof(num.c_str());
cout << r << endl;
}
输出为:
135428
我要:
135427.7
cout
这样做,而不是 atof()
。
更准确地说,operator<<
,它将格式化数据插入 std::ostream
。
您可以使用 std::setprecision()
from the <iomanip>
标准库来打印小数:
cout << setprecision(7) << r << endl;
或
cout << fixed << setprecision(1) << r << endl;
如果要打印整个135427.7000
:
cout << fixed << setprecision(4) << r << endl;