-1

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
IronMensan
  • 6,761
  • 1
  • 26
  • 35
padmanabhanm
  • 315
  • 3
  • 15
  • While it's fairly obvious what's wrong here, a general tip is to give just a couple of test cases that show your error (rather than every 20 degrees from 0 to 280), and state explicitly what result you expected to get. – me_and Sep 15 '12 at 21:57

3 Answers3

2

5/9 is zero in whole numbers, try cel=(fahr-32)*5/9 or float the whole boat.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • `fahr` is an `int` too, so the reordering doesn't change anything, you need at least one `x.0` or cast in that. – Daniel Fischer Sep 14 '12 at 18:07
  • @DanielFischer, reordering does a great deal, because after multiplying `(fahr-32)` by 5 division by nine is much more meaningful. And will actually yield sane values. To have all the precision float is helpful, tho. – Michael Krelin - hacker Sep 14 '12 at 18:11
  • 1
    Right, overlooked that, you'll get 0 only for values between 31 and 33, which is not obscenely far off. – Daniel Fischer Sep 14 '12 at 18:14
  • Yes, the only problem is that `float` for `cel` makes no sense if calculation is done in integers. Loss of precision may be justified if there's no float involved. – Michael Krelin - hacker Sep 14 '12 at 18:17
2

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.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
0

Give this a try:

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);   
  } 
}

5/9 is (as a type) int/int which will give an int. You can convert the math by changing them to 5.0/9.0, or you can just 5./9.

Mike
  • 47,263
  • 29
  • 113
  • 177