浮点的小数点



我对C++业务还是个新手。我想输出一个只有一个十进制数的浮点数。起初我认为它可以使用Modulo(%(,但我很快就放弃了。然后我想计算它,但我解决不了这个。还有一条线索。我只能使用<iostream><fstream>。但现在我遇到了函数setprecision((。

我的输出代码是。cout<<fixed<<setprecision(2)<<variable<<endl;然而,它输出例如2.99。不过我需要2.9。cout<<fixed<<setprecision(1)<<variable<<endl;输出3.0。

请帮帮我,我将不胜感激

在评论中说明Sebastian的浮点环境解决方案

#include <fenv.h>
#include <iostream>
#include <iomanip>
int main() {
    if (fesetround(FE_TOWARDZERO)) {
        // need to check for non-zero error condition
        std::cerr << "Unable to set correct rounding direction" << std::endl;
        return 1;
    }
    float value = 2.99f;
    std::cout << std::setprecision(2) << value << std::endl;
}

这将打印

2.9

请注意,这也会影响其他浮点计算,这可能会导致意外的结果。

我不知道在不同的目标体系结构上对这些不同的舍入方向的支持有多广泛,所以如果你想要极端的可移植性,如果fesetround返回非零值,你需要提供一个备份解决方案。

导螺杆

这里有一种方法:

#include <math.h>
#include <iostream>
int main() {
    auto f = 2.9999;
    std::cout << trunc(f * 10) / 10 << 'n';
}

Sebastian在评论中解决了这个问题。

cout<< fixed<<setprecision(1)<<variable-.05<<endl;

感谢大家的贡献。我会努力提高

最新更新