Search code examples
c++double

Double acts weird in C++


I am trying to make a small graphics demo, and was increasing a variable (let's say it's called B) by 0.05 every iteration. Problem, the code does not work as expected.

#include <iostream>

int main(void)
{
    double b = 0;
    for (int i = 0; i < 3001; ++i) {
        if (b < 150)
            b += 0.05;
        std::cout << b << std::endl;
    }
}

The expected outcome is for the last results to be "150.00", or "150", but instead it prints "150.05". Somehow, the code runs the b += 0.05; one more time. I honestly do not know how to search for a fix on the internet, there's no way I can word this error in a short sentence.


Solution

  • It is because of double precision. You can solve it by using integers:

    int main(void)
    {
        int b = 0;
        for (int i = 0; i < 3001; ++i) {
            if (b < 15000)
                b += 5;
            std::cout << b/100 << std::endl;
        }
    }