Abhijeet Sridhar
Abhijeet Sridhar

Reputation: 89

Why is float in c not working the way it should?

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.

Upvotes: 0

Views: 104

Answers (1)

pmg
pmg

Reputation: 108988

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.

Upvotes: 1

Related Questions