0

我正在开发一个程序,用户输入一个双精度数,然后我将双精度数拆分并将其放入一个数组中(然后我做一些其他的事情)。问题是,我不确定如何按数字拆分双精度,并将其放入一个 int 数组中。请帮忙?

这是我要找的东西:

    double x = 999999.99 //thats the max size of the double
    //I dont know how to code this part
    int[] splitD = {9,9,9,9,9,9}; //the number
    int[] splitDec = {9,9}; //the decimal
4

3 回答 3

2

您可以转换数字,String然后根据.字符拆分字符串。

例如:

public static void main(String[] args) {
        double x = 999999.99; // thats the max size of the double
        // I dont know how to code this part
        int[] splitD = { 9, 9, 9, 9, 9, 9 }; // the number
        int[] splitDec = { 9, 9 }; // the decimal

        // convert number to String
        String input = x + "";
        // split the number
        String[] split = input.split("\\.");

        String firstPart = split[0];
        char[] charArray1 = firstPart.toCharArray();
        // recreate the array with size equals firstPart length
        splitD = new int[charArray1.length];
        for (int i = 0; i < charArray1.length; i++) {
            // convert char to int
            splitD[i] = Character.getNumericValue(charArray1[i]);
        }

        // the decimal part
        if (split.length > 1) {
            String secondPart = split[1];
            char[] charArray2 = secondPart.toCharArray();
            splitDec = new int[charArray2.length];
            for (int i = 0; i < charArray2.length; i++) {
                // convert char to int
                splitDec[i] = Character.getNumericValue(charArray2[i]);
            }
        }
    }
于 2013-03-12T00:40:07.323 回答
0

有几种方法可以做到这一点。一种是首先获取 的整数部分double并将其分配给int变量。然后您可以使用/and%运算符来获取 that 的数字int。(事实上​​,这将是一个漂亮的函数,因此您可以在下一部分中重用它。)如果您知道您只处理最多两位小数,您可以从双精度数中减去整数部分以获得小数部分部分。然后乘以 100 并得到与整数部分一样的数字。

于 2013-03-12T00:34:23.890 回答
0

您可以从双重创建一个字符串:

String stringRepresentation  = Double.toString(x);

然后拆分字符串:

String[] parts = stringRepresentation.split("\\.");
String part1 = parts[0]; // 999999
String part2 = parts[1]; // 99

然后使用以下方法将其中的每一个转换为您的数组:

int[] intArray = new int[part1.length()];

for (int i = 0; i < part1.length(); i++) {
    intArray[i] = Character.digit(part1.charAt(i), 10);
}
于 2013-03-12T00:39:57.060 回答