-3
public void mystery1(int n) {
if (n <= 1) {
    System.out.print(n);
} else {
    mystery1(n / 2);
    System.out.print(", " + n);
}
}

What gives this code for odd numbers. Becuase when we divide it it will not be an integer.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
ferit enişer
  • 41
  • 1
  • 8

4 Answers4

1

There is not mystery, because result of the integer division in Java is integer.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
1

In Java or most other programming languages, when you divide an integer by an integer, the result will be an integer. If a decimal number occurs, say for example:

5/2=2.5

then, the number before the decimal point will be treated as the integer and 2 will be chosen.

In case you want to explicitly convert the integer into float or double, you can use any of the following conversions:

(float) 3/2;

(double) n/2;

The above explicitly converts it to a decimal.

Next Door Engineer
  • 2,818
  • 4
  • 20
  • 33
  • @LouisWasserman: I have mentioned that it takes the floor function of the number. So the floor of (-1/2) would be 0. – Next Door Engineer Jul 31 '12 at 11:43
  • Traditionally, [no,](http://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Examples) that's not what "floor" means, even [as used in Java itself](http://docs.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#FLOOR). – Louis Wasserman Jul 31 '12 at 21:12
0

n / 2, this is an integer division, where the fraction part will be ignored.

System.out.println(3/2); // prints 1
System.out.println(3.0/2); // prints 1.5
System.out.println(3/2.0); // prints 1.5
System.out.println(3.0/2.0); // prints 1.5
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

Param will rounded to int, for example if param will be 5, the next call the function will be with param 2

Dedyshka
  • 421
  • 3
  • 10
  • 20