1

The code below should output the each 10th term (0.0, 10.0, 20.0, etc...) till 100.0. But it outputs only "0". Does anyone know what's the problem?

include <iostream>
include <cmath>
using namespace std;

for (double t = 0.0; t < 100.0; t += 0.1)
{
    if (remainder(t, 10.0) == 0)
    {
        cout << t << "\n";
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

2

You're working with floating-point numbers which have inherent inaccuracy. remainder returns a float value and checking the value exactly to 0 with == doesn't always work.

You need to use a tolerance and see if the remainder is in the bounds of the tolerance as:

#include <iostream>
#include <cmath>

int main()
{
    for (double t = 0.0; t <= 100.0; t += 0.1)
    {
        if (std::abs(std::remainder(t, 10.0)) <= 0.001)
        {
            std::cout << t << "\n";
        }
    }
}

Note: further reading.

CK.
  • 312
  • 3
  • 13
  • The whole Q&A of "further reading" is important the the OP (and any programmer!) but the part that points directly to the OP's problem here is the bit about 0.1 not being exactly representable in binary. (Just pointing him to it, for convenience.) – davidbak Jan 10 '19 at 17:14