1

I can't seem to figure out why it's not printing correctly:

public class test3 {
  public static void main(String[] args) {
    double[] gens = {100, 200.1, 9.3, 10};
    double d0 = 0;
    double d1 = 0;
    double d2 = 0;
    double d3 = 0;
    double d4 = 0;
    double d5 = 0;
    double d6 = 0;
    double d7 = 0;
    double d8 = 0;
    double d9 = 0;
    for (int i = 0; i < gens.length; i++) {
      double percs = gens[i];
      while (percs < -9 || 9 < percs) percs /= 10;
      percs = Math.abs(percs);
      if (percs == 0) {
        d0 += 1;
      }
      else if (percs == 1) {
        d1 += 1;
      }
      else if (percs == 2) {
        d2 += 1;
      }
      else if (percs == 3) {
        d3 += 1;
      }
      else if (percs == 4) {
        d4 += 1;
      }
      else if (percs == 5) {
        d5 += 1;
      }
      else if (percs == 6) {
        d6 += 1;
      }
      else if (percs == 7) {
        d7 += 1;
      }
      else if (percs == 8) {
        d8 += 1;
      }
      else if (percs == 9) {
        d9 += 1;
      }
    }
    double[] pack = {
       d0 /= gens.length,
       d1 /= gens.length,
       d2 /= gens.length,
       d3 /= gens.length,
       d4 /= gens.length,
       d5 /= gens.length,
       d6 /= gens.length,
       d7 /= gens.length,
       d8 /= gens.length,
       d9 /= gens.length
    };
    System.out.println(pack[0]);
    System.out.println(pack[1]);
    System.out.println(pack[2]);
    System.out.println(pack[3]);
    System.out.println(pack[4]);
    System.out.println(pack[5]);
    System.out.println(pack[6]);
    System.out.println(pack[7]);
    System.out.println(pack[8]);
    System.out.println(pack[9]);
  }
}

I know it's pretty repetitive, but that's just how I'm dealing with it for now.

Anyway, essentially, it should take those four numbers in the gens array, cut them off to the first digit of each number (i.e. 1, 2, 9 & 1 respectively), then count how many times each digit from 0-9 shows up, so '1' should give 0.5 (50%), 2 should give .25 (25%) and 9 should give .25 (25%) where every other digit from 0-9 should give 0. I get 0.5 for the digit '1', but 0 for every other one, and I haven't been able to find my mistake. The results I get vary depending on which numbers I input (hardcode), but they're pretty much always wrong.

Any ideas?

Thank you!

4

2 回答 2

5

改变

double percs = gens[i];

int percs = (int)gens[i];

如果您将其保留为双精度,则您的 while 循环

while (percs < -9 || 9 < percs) percs /= 10;

不会正确切断除第一个数字之外的所有数字,因为它将执行正常除法而不是整数除法。如果您percs在 while 循环之后打印,您可以看到这一点。


我还想指出,这可以容易地完成。例如:

double[] gens = {100, 200.1, 9.3, 10};

int[] count = new int[10];

for (double d : gens)
    count[("" + Math.abs(d)).charAt(0) - '0']++;

for (int n : count)
    System.out.println((double)n / gens.length);

会做同样的事情。

于 2012-10-24T21:20:43.217 回答
1

如果您percs在每个阶段打印出来,您会注意到它们是:

1.0
2.001
0.93
1.0

所以你的 == 将不起作用。这是因为您正在划分双精度数而不是整数。您可以改为使用:

int percs = (int) gens[i];

这将为您提供所需的整数值。

于 2012-10-24T21:24:23.630 回答