打印带有十进制近似值的int []数组

时间:2016-11-10 18:24:11

标签: java arrays

如何使用int []数组返回带有十进制近似值的序列[1 / 1,1 / 2,1 / 3]等数组?到目前为止我试过这个:

public static int[] decimalApproximations (int arraySize) {
    int [] sequence = new int[arraySize];
    for(double i = 1; i <= arraySize; i++) {
        sequence[(int)(i)-1] = (int)(1.0/i);
    }
    return sequence;
}

但由于int截断,它仍然为1/1和0打印1。是否有可能在此数组中使用十进制近似值?

2 个答案:

答案 0 :(得分:2)

正如评论中所提到的,int数组不能存储十进制值,但是如果你想要一个包含序列的数组,这可能会有所帮助:

  public double[] decimalApproximations (int arraySize) {
    double [] sequence = new double[arraySize];
    for(int i = 0; i < arraySize; i++) {
        sequence[i] = 1.0/(i+1);
    }
    return sequence;
}

答案 1 :(得分:0)

只需将您的int更改为double

public static double[] decimalApproximations (int arraySize) {
    double[] sequence = new double[arraySize];

    for(double i = 0; i < arraySize; i++) {
        sequence[i] = 1.0/(i+1);
    }

    return sequence;
}