Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does trunc() return 0?

I was stuck in the above problem.

While trying to solve that, I wrote the following listing.

I expect it to keep two digits after the decimal point.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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
}

Output:

-4.84292e-06
6.82474e-08
-0
0

>Solution :

-4.84292e-06 and 6.82474e-08 are still zero within two digits after the decimal point, so as expected, you’re getting zero when truncating them.

If you wrote

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

… then you would print 0.00 instead of 0. It keeps two digits after the decimal point, and both those digits are zero.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading