-1

I have this code and I want to print all the numbers of an arithmetic progression of ratio 0.3 but when I use the following code it includes 3, when I wanted all non-negative below 3. What would be another way to do it?

#include <stdio.h>

int main() {
    double x = 0;
    while(x < 3.0) {
        printf("x = %f\n", x);
        x += 0.3;
    }
    return 0;
} 
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • 2
    Ah! You need to understand that `2.99999999987534233652` is less than `3.0` and displays as `3.000000`. See ["What Every Programmer Should Know About Floating-Point Arithmetic"](https://floating-point-gui.de/) – pmg Apr 20 '22 at 17:17
  • see https://ideone.com/Klb7Ro – pmg Apr 20 '22 at 17:19
  • also [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – yano Apr 20 '22 at 17:20

1 Answers1

0

3/10 is a periodic number in binary just like 1/3 is a periodic number in decimal. As such, it can't be accurately represented by a floating point number.

$ perl -e'printf "%.100g\n", 0.3'
0.299999999999999988897769753748434595763683319091796875

(Used Perl here because it was terser. The choice of language isn't important because it's a property of floating point numbers, not the language.)

In your case, the problem can be avoided by scaling the numbers up by a factor of ten.

#include <stdio.h>

int main() {
    int x = 0;
    while(x < 30) {
        printf("x = %f\n", x/10.0);
        x += 3;
    }

    return 0;
}
ikegami
  • 367,544
  • 15
  • 269
  • 518