-1
import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     int tempC = input.nextInt();
     float tempF = (tempC * 9 / 5) + 32;
     System.out.println(tempF);
   }
}

Expected output - 109.4

Current output - 109.0

Why decimal value set to zero?

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
  • Does this answer your question? [Division of integers in Java](https://stackoverflow.com/questions/7220681/division-of-integers-in-java) – ndc85430 Jun 16 '23 at 04:13
  • 1
    *"Multiplication of int with float resulting wrong."* - The problem is that you are NOT multiplying an int and a float. You are multiplying and dividing ints! – Stephen C Jun 16 '23 at 04:22
  • Design question: Why is `TempC` an int if you expect temperatures to have fractional parts? Making it a float too would automatically solve the problem in the computation. – Lutz Lehmann Jun 16 '23 at 04:43

1 Answers1

0

"... Why decimal value set to zero?"

The reason this is happening is because the division of two int values will result in an integer value, as opposed to a real—float or double.

You can remedy this by appending the float or double literal-suffix, to the end of either of those values.

Here is an except from the Java Tutorials.
Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics).

"... A floating-point literal is of type float if it ends with the letter F or f; otherwise ... double and ... letter D or d. ..."

Only one literal-suffix is required, per arithmetic statement.  So the following will suffice.

tempC * 9 / 5f

As a final note, you could specify a double by simply writing it as 5.0.
Although, you would then have to change tempF to a double.

double tempF = (tempC * 9 / 5.0) + 32;
Reilas
  • 3,297
  • 2
  • 4
  • 17