首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印4小数点的最大值

打印4小数点的最大值
EN

Stack Overflow用户
提问于 2016-12-19 19:44:39
回答 2查看 490关注 0票数 5

我试图在C++小数点之后打印最多4位数字(使用流)。所以,如果这个数字不需要小数点之后的4位,我希望它只使用它实际需要的小数数。

示例:

代码语言:javascript
复制
1.12345    -> 1.1234
1.0        -> 1
1.12       -> 1.12
1.12345789 -> 1.1234
123.123    -> 123.123
123.123456 -> 123.1234

我尝试了std::setprecision(4),但是这设置了有效数字的数量,但是在测试用例中失败了:

代码语言:javascript
复制
123.123456 gives 123.1

我还尝试将std::fixedstd::setprecision(4)一起给出,但这在小数点之后给出了一个固定的数字,即使不需要:

代码语言:javascript
复制
1.0 gives 1.0000

std::defaultfloat似乎是我所需要的,不是固定的,也不是指数的。但是它似乎没有适当地打印十进制后的数字数,并且只有一个重要数字的选项。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-19 20:31:51

我们可以使用std::stringstreamstd::string来实现这一点。我们将double传递给流,将其格式化,就像将它发送到cout一样。然后,我们检查从流中得到的字符串,看看是否有尾随零。如果有,我们就除掉他们。一旦我们这样做,我们检查是否只剩下小数点,如果我们是,那么我们也摆脱了它。你可以用这样的东西:

代码语言:javascript
复制
int main()
{
    double values[] = { 1.12345, 1.0, 1.12, 1.12345789, 123.123, 123.123456, 123456789, 123.001 };
    std::vector<std::string> converted;
    for (auto e : values)
    {
        std::stringstream ss;
        ss << std::fixed << std::setprecision(4) << e;
        std::string value(ss.str());
        if (value.find(".") != std::string::npos)
        {
            // erase trailing zeros
            while (value.back() == '0')
                value.erase(value.end() - 1);
            // if we are left with a . at the end then get rid of it
            if (value.back() == '.')
                value.erase(value.end() - 1);
            converted.push_back(value);
        }
        else
            converted.push_back(value);
    }
    for (const auto& e : converted)
        std::cout << e << "\n";
}

当被制作成运行示例

代码语言:javascript
复制
1.1235
1
1.12
1.1235
123.123
123.1235
123456789
123.001
票数 4
EN

Stack Overflow用户

发布于 2016-12-19 20:34:44

使用来自这里的答案和自定义逻辑移除零和点:

代码语言:javascript
复制
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

std::string remove_zeros(std::string numberstring)
{
    auto it = numberstring.end() - 1;
    while(*it == '0') {
        numberstring.erase(it);
        it = numberstring.end() - 1;
    }
    if(*it == '.') numberstring.erase(it);
    return numberstring;
}

std::string convert(float number)
{
    std::stringstream ss{};
    ss << std::setprecision(4) << std::fixed << std::showpoint << number;
    std::string numberstring{ss.str()};
    return remove_zeros(numberstring);
}

int main()
{
    const float values[]{1.12345, 1.0, 1.12, 1.12345789, 147323.123, 123.123456};
    for(auto i : values)
        std::cout << convert(i) << '\n';
}

生产:

代码语言:javascript
复制
1.1235
1
1.12
1.1235
147323.125
123.1235
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41229910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档