我被上面的问题困住了。
在尝试解决这个问题时,我编写了以下清单。
我希望它保留小数点后两位数。
#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
-4.84292e-06
6.82474e-08
小数点后两位数内仍然为零,因此正如预期的那样,截断它们时您会得到零。如果你写了
...然后你会打印
0.00
而不是0
. 它在小数点后保留两位数字,并且这两位数字都是零。