0

I have tried this in Javascript and have gotten my answers, but the answer I need must be more exact. I am trying to divide 1 by every number between 2 and 1000, and simply print them.

public static void main(String [] args) {
    for (int i=2;i<=1000;i++){
        double g = (1/i);
        System.out.println(g); // print "1/1,2,3,4.....1000" 
    }
}

I haven't done Java in a while, so I forget my correct variable names.

user2962770
  • 11
  • 1
  • 3

4 Answers4

4

Since both 1 and i are integers, integer division is being used. Either 1 or i need to be double in the 1/i section of your code so that integer division is not used. You can do something like 1.0/i or 1/((double) i) to ensure that float division is used instead.

stiemannkj1
  • 4,418
  • 3
  • 25
  • 45
2

replace 1 by 1.0D that will result into double

jmj
  • 237,923
  • 42
  • 401
  • 438
0

try this

public static void main ( String args[] )  {

            for (int i=2;i<=1000;i++){
                double g = (1.0/i);
                System.out.println("1/"+ig); 
            }

output: 0.5 0.3333333333333333 0.25 0.2 0.16666666666666666 0.14285714285714285 0.125 . . . .

Nambi
  • 11,944
  • 3
  • 37
  • 49
0

I would do something like this (note you can have as many digits of precision as you like) utilizing BigDecimal.

public static void main(String[] args) {
  java.math.BigDecimal ONE = java.math.BigDecimal.ONE;
  // 50 digits of precision.
  java.math.MathContext mc = new java.math.MathContext(50);

  for (int i = 2; i <= 1000; i++) {
    java.math.BigDecimal divisor = new java.math.BigDecimal(i);
    java.math.BigDecimal result = ONE.divide(divisor, mc);
    result.round(mc);
    System.out.printf("%d/%d = %s\n", 1, i,
        result.toString());
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249