0

I was trying to do the codechef question - https://www.codechef.com/problems/FLOW009

Here, my code (submitted successfully )is this -

int main(void) {

   int testCases;

   scanf ("%d\n", &testCases);
   while (testCases--) {

       float q,p;
       scanf ("%f%f", &q,&p);

       if (q >= 1000){

           printf("%.6f\n",q*p - (q*p*0.1));
       }
       else{
           printf("%.6f\n", q*p);
       }

   }

   return 0;
} 

This was submitted successfully... But however when i tried this code -

int main(void) {

   int testCases;

   scanf ("%d\n", &testCases);
   while (testCases--) {

       float q,p;
       scanf ("%f%f", &q,&p);

       if (q >= 1000){
           float a = q*p - (q*p*0.1);
           printf("%.6f\n",a);
       }
       else{
           printf("%.6f\n", q*p);
       }

   }

   return 0;
} 

It said wrong answer. In my compiler the results are same for all the test cases. What is happening. The first code- i am just printing the value. In the second - i am using a variable to store the value.

PS - i tried typecasting the value also but with no result.

  • The short answer is that "0.1" cannot be represented exactly in binary floating point. Likely the two pieces of code were optimized differently with the one that worked keeping more precision internally. (Similar to how in decimal, "3 x 1/3" might give you one, but if you store 1/3 in a variable, it might get rounded to "0.3333333" which won't equal 1 when multiplied by 3.) – David Schwartz Dec 13 '16 at 09:24
  • 2
    The codechef problem description also requires all inputs to be integral which sort of suggests that calculations should be using integers too. – Peter Dec 13 '16 at 09:30
  • Note: `0.1` is of type `double`. – pmg Dec 13 '16 at 09:40
  • Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Toby Speight Dec 13 '16 at 09:58

1 Answers1

1

Converting a value from double to float and back does not guarantee the same result.

In

printf("%.6f\n", q*p - (q*p*0.1));

the values are all converted to type double and the calculation is done in double. The result, of type double, is sent directly to printf.

In the other case with the float variable, the values are converted to double, the calculation is done in double then converted to float for the assignment. That value is converted to double before being passed on to printf.

Always use double for floating point variables.

pmg
  • 106,608
  • 13
  • 126
  • 198