Introduction to Algorithm Competition Classics (4) – Floating-Point Pitfalls

Words: 131

Competitive Programming Getting Started Classic (2nd Edition)
P36 Problem 2: What is the output of the following program? The “!=” operator means “not equal”. Hint: please run it on a computer, and do not answer based on subjective intuition.

cpp
1
2
3
4
5
6
7
#include<stdio.h>
int main() {
    double i;
    for(i=0; i!=10; i+=0.1)
        printf("%.lf\n",i);
    return 0;
}

Run result:

You can see that the program will keep looping forever
Change the code to the following

cpp
1
2
3
4
5
6
7
#include<stdio.h>
int main() {
    double i;
    for(i=0; i!=10&&i<20; i+=0.1)
        printf("%.lf\n",i);
    return 0;
}

You can see

In C, computations involving the double type have errors
That is, each time you add 0.1
you may never get exactly 10

Therefore the above program will loop forever

Loading...