Question:
Why ((2 / 3) + (1 / 3) - 1) is equal to -1 in java?
Trol
2018-09-24 19:49:14 UTC
I execute this program in netbeans using java and the output I receive is -1, why?
public class MyClass {
public static void main(String args[]) {
float x;
x= (((2 / 3) + (1 / 3) )- 1 );
System.out.println(x);

}
}
Three answers:
Russ in NOVA
2018-09-24 20:00:34 UTC
Because you are using Integers in the equation, it is doing Integer arithmetic and doesn't convert to float until after the equation is is assigned to x. In java integer arithmetic 2/3 and 1/3 both result as 0 since java truncates in integer division. It is the same as:

x=( (0)+(0)-1 )



To get the answer you want, use floating point constants:

x = ( (2.0/3.0) + (1.0/3.0) - 1.0) and actually x = ( (2.0/3) + (1.0/3) - 1) will work if I recall, mixed integer and float results as a float.
brilliant_moves
2018-09-24 19:59:12 UTC
@Chris is right. If you want correct result, change the 3 to 3.0 like so:



x=(((2/3.0) + (1/3.0)) -1);
Chris
2018-09-24 19:54:11 UTC
Integer division. 2 / 3 equals 0, and so does 1 / 3.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...