0
Iclass Solution
{
   public double cToF(int C)
   {
        //Your code here
        double fh;
        fh = (C*(double)(9/5))+32; //C=32 F=64
        
        return fh;
   }
}

IIclass Solution
{
    public double cToF(int C)
    {
        //Your code here
        double fh; 
        fh = (C*1.8)+32; //C=32 F=89
        
        return fh;
    }
}

Please take a look on the above code. This code mainly coverts temperature from Celsius to Fahrenheit. In the code I, when I used (9/5) in formula, I got the answer as 64. But in code II, when I used 1.8(9/5=1.8), I got as 89(correct one). Could anyone explain the logic behind that?

  • You are doing integer division in `9 / 5` It is not ambiguous ... just the wrong thing to do in this context. In Java `9 / 5` gives `1`. – Stephen C Jan 23 '22 at 06:04
  • 9/5 equals 1, since that's int division, so the result is int. You can use 9.0/5 – Eran Jan 23 '22 at 06:05

1 Answers1

0

Actually when you divide 9/5, it takes 9 as well as 5 as an integer and then, it evaluates the whole answer as integer only. Thus, 9/5 (which is actually 1.8) is then type casted from 1.8 to 1. The portion after decimal is truncated. Thus, in your first code, it multiplies everything with 1 so it gives wrong output.

Now you'll ask, I have type casted into double then why?

Well, the answer is that first it evaluates 9/5 which is equal to 1 (according to int division by computer). Then it type castes 1 into double i.e. 1.0. Thus, you can instead use 9.0/5.0. This will also give you correct answer.

Utkarsh Sahu
  • 409
  • 3
  • 16