1

1)double d = 1.234567899;
将此数字转换为小数点后 8 位不截断的字符串。因此,预期输出为“1.23456789”,截断最后 9 个。

2)if d = 1.2345699;
所以解决方案不应将 0 附加到小数点后 8 位。预期输出“1.2345699”。

我尝试了很多解决方案,最终得到了 stringstream c++ 类。第二个问题解决了,但第一个问题仍然存在。

有没有办法实现输出?

提前致谢。

4

3 回答 3

2

如果要截断部分字符串表示而不进行舍入,则需要手动执行此操作:

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <limits>

int main()
{
        std::stringstream s;
        double d = 1.234567899;

        // print it into sstream using maximum precision
        s << std::fixed << std::setprecision(std::numeric_limits<double>::digits10) << 1.234567899;
        std::string res = s.str();

        // Now the res contains something like 1.234567899000000
        // so truncate 9000000000 by hand

        size_t dotIndex = res.find(".");

        std::string final_res = res.substr(0, dotIndex + 9);

        std::cout << final_res << std::endl;

        return 0;
}
于 2013-09-20T09:52:31.577 回答
0

完全按照您的意愿截断:

sprintf(str, "%1.10f", d);
memset(str+10, 0x00, 1);
于 2013-09-20T10:35:42.960 回答
0

您是否会先将双倍数设置为所需的小数点?如果是这样,请查看http://www.cplusplus.com/forum/beginner/3600/

于 2013-09-20T09:51:35.747 回答