ZelluX
ZelluX

Reputation: 72605

A strange print function bug

I'm working on a InterviewStreet problem https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817, the algorithm is correct but I still get several wrong answers, after several hours I find the problem is related with a print function:

void printHalf(int64_t x) {
    if (x % 2 == 0)
        printf("%lld\n", x / 2L);
    else
        printf("%lld.5\n", x / 2L);
}

This function takes a 64-bit integer, and print its half. If I change this function to the following code, my solution works on all test cases:

void printHalf(int64_t x) {
    if (x % 2 == 0)
        printf("%lld\n", x / 2L);
    else
        printf("%.1f\n", x / 2.0);
}

It looks a little weird to me, since in my opinion the two functions have the same results.

Upvotes: 0

Views: 82

Answers (1)

interjay
interjay

Reputation: 110088

Your first version doesn't handle the value -1 properly. If you run printHalf(-1) it will print 0.5, because it doesn't know that it needs to display -0 instead of 0.

For other negative values, it will work correctly in C++11, but relies on implementation-defined behavior in C++03 (the C++03 standard doesn't specify how division of negative numbers is rounded).

The second version may also print incorrect results: If the value is very large, the conversion to floating-point will reduce accuracy (since double-precision floating point can't represent all 64-bit integers accurately), so the result may be off by a little.

Upvotes: 3

Related Questions