-1

So, I have this code which is the beginning of an RSA-encrypter (current math class). Now I'm still in the beginning stages and I notice that when I try to make an array of doubles, they all come out to the screen as whole numbers, what's going on here ?

As you can see in the code I divide the multiples of 7 by 40 and it should come out as fractions (7 / 14 = 0.175 for example) but instead as 0.0. Help


import java.util.*;

public class Encryption {

static double[] ads = new double[200];

public static void main(String args[]){
    for(int i = 0; i < 200; i++){
        ads[i] = (7 * i) / 40;
    }

    for(int i = 0; i < ads.length; i++){
        System.out.println(ads[i]);
    }
  }
}

1 Answers1

2

It's because you're storing an integer into the array in the first place.

Consider this line:

ads[i] = (7 * i) / 40;

In the expression on the right, you first multiply i by 7, then divide it by 40. i is an integer. So, let's say i == 1. Then, 7 * i == 7, which is still an integer. Both 7 and 40 are integers, so when you evaluate 7 / 40, you get integer division. Integer division always rounds down. When the result gets stored into ads[i], it gets converted to a double, but by that point it's already been rounded down.

Try changing this line to the following:

ads[i] = (7 * i) / 40.0;

This works because 40.0 is a double, not an int.

In unrelated news, if you're using double to implement RSA, you're probably doing something wrong. Doubles aren't infinitely precise, and will screw up your result.

IanPudney
  • 5,941
  • 1
  • 24
  • 39