'Print arithmetic progression below a number [duplicate]

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;
} 
c


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1