为什么 trunc() 返回 0?

问题描述 投票:0回答:1

我被上面的问题困扰了。

在尝试解决这个问题时,我编写了以下清单。

我希望它保留小数点后两位。

#include "simulation.hpp"
#include <cstdio>

typedef double real;

double truncate_(double f)
{
    return std::trunc(f * 100.0);
}

int main()
{
    //Simulation sim;
    //sim.run();
    LennardJones lj(Constants::EPSILON, Constants::SIGMA, Constants::KB);

    Vec3 diatance(4.0, 4.0, 4.0);

    real attractive = lj.getPotentialAttractive(diatance);
    real repulsive = lj.getPotentialRepulsive(diatance);

    std::cout << attractive << std::endl;
    std::cout << repulsive << std::endl;

    real attractive2 = truncate_(attractive);
    real repulsive2 = truncate_(repulsive);

    std::cout << attractive2 << std::endl;
    std::cout << repulsive2 << std::endl;

    getchar(); // Wait for a keypress
}

输出:

-4.84292e-06
6.82474e-08
-0
0
c++ truncate
1个回答
1
投票

-4.84292e-06
6.82474e-08
在小数点后两位数内仍然为零,因此正如预期的那样,截断它们时您会得到零。

如果你写了

std::cout << std::fixed << std::setprecision(2)

...那么您将打印

0.00
而不是
0
。它保留小数点后两位数字,并且这两位数字都是零。

© www.soinside.com 2019 - 2024. All rights reserved.