Francesco Mantovani :
I'm new to Java and I'm learning the first steps.
Doing my homework I have a problem printing a total with a floating point:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Francesco");
int myFirstNumber = (10 + 5) + (2 * 10);
int mySecondNumber = 12;
int myThirdNumber = myFirstNumber * 2;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
float myLastOne = myTotal/10;
System.out.println(myTotal);
System.out.println(myLastOne);
}
}
What Java prints is 11.0
:
Hello, Francesco
117
11.0
But instead it should print 11.7
:
Hello, Francesco
117
11.7
I know that the problem reside in line numbers 8 where I'm using float
, I even tried using double
but I have the same result
azro :
This is because of int-division
as 10
is an int
. You need to add the suffix f fo specify it's a float
float myLastOne = myTotal / 10f;
System.out.println(myLastOne); // 11.7
This would work also with double
double myLastOne = myTotal / 10.0;
System.out.println(myLastOne); // 11.7
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=389102&siteId=1