Search code examples
cmingw32

I tried my first program in mingw. And i got the following output. What is wrong in my program?


Program:

#include<stdio.h>
main()
 {
  int fahr;
   float cel;
   for(fahr=0;fahr<300;fahr=fahr+20)
   {
   cel=(5/9)*(fahr-32);
     printf("\n %d \t %f",fahr,cel);
    }
}

Output which i get:

   0       0.000000
   20      0.000000
   40      0.000000
   60      0.000000
   80      0.000000
   100     0.000000
   120     0.000000
   140     0.000000
   160     0.000000
   180     0.000000
   200     0.000000
   220     0.000000
   240     0.000000
   260     0.000000
   280     0.000000

Solution

  • Division between two ints always results in another int. If one of the two terms is a float or a double the other one gets automatically promoted to that type, thus yelding the correct result.

    So typeof(5/9) = int while typeof(5.0/9) = typeof(5/9.0) = typeof(5.0/9.0) = double.

    Therefore the correct version is:

    cel=(5./9.)*(fahr-32); 
    

    Note: This happens everytime there's a mathematical expression with types of different 'rank', types of lower ranks are promoted to match the highest.