-2

I want my output to be

0----2----4----6----8----1----1----1----1

but I keep getting

0----2----------------------------------

Basically i want to count from 0 to 16 in increments of 0.4. Here is my code:

int
main(int argc, char *argv[]) {
    double x;
    for( x = 0.0; x<= 16.0; x = x + 0.4){

        if( fmod(x,2.0) == 0){
            if(x< 10){
                printf("%.0f",x);
            }

            if(x >= 10){
                printf("%.0f",x/10);
            }
        }

        else{
            putchar('-');
        }
    }

    printf("\n");


    return 0;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Pyrons
  • 325
  • 1
  • 5
  • 12
  • 4
    floating point precision: fmod(x,2.0) == 0 – Mitch Wheat Sep 08 '14 at 01:24
  • Please do not delete your code once you get an answer. This is a public Q&A site, and we want the questions to be useful to others in the future. – John Kugelman Sep 08 '14 at 02:16
  • 1
    0.4 cannot be represented in binary floating point, so you can't get exact 2.0 http://stackoverflow.com/questions/588004/is-floating-point-math-broken http://stackoverflow.com/questions/5599912/why-do-floats-seem-to-add-incorrectly-in-java read this http://floating-point-gui.de/ [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – phuclv Sep 08 '14 at 03:55

1 Answers1

1

Your problem is due to floating point precision and attempting an exact comparison here:

if (fmod(x,2.0) == 0)

Either use integers, or use an 'epsilon' test:

epsilon = 0.000001;
if (fabs(fmod(x,2.0)) < epsilon)
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541