0
How is 15/4=3?
This exercise must be wrong: What is the result of the following code? int x = 15; int y = 4; int result = x / y; System.out.println(result); the result should be some error code, but the system unlock says "3". Is it a typo? should it have been 12 instead of 15?
5 Answers
+ 4
3 is correct. int will only hold integers, so whole numbers. Everything else will be truncated, which means cut off. It's important to understand that truncating does not mean rounded.
So if 15 / 4 = 3 with a remainder of 3, the remainder is truncated, leaving us with just 3.
+ 2
In Java, when both operands are integers, the / operator performs the euclidian division. To avoid this, cast one of the operand into a float or double before making the division. Also, the int data type can't hold decimal values, so result has to be a float or double as well.
int x = 15; int y = 4;
double result = (double)x / y;
System.out.println(result);
0
you use int instead of using double
if you use int you will get your answer in interger form .
but if you change int with double you will get your output in Decimal form.... hopefully you understand?
0
I thought it would be 4 because it would be rounded to the nearest whole number but that was stupid lol