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から文字列を作成できます。

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 に答える
0

これを行うにはいくつかの方法があります。1 つは、最初に の整数部分を取得し、それを変数doubleに割り当てることです。int次に、/and%演算子を使用して、その数字を取得できますint。(実際、これは気の利いた関数になるので、次の部分で再利用できます。) 小数点以下 2 桁までしか扱っていないことがわかっている場合は、double から整数部分を引いて分数を得ることができます。部。次に、100 を掛けて、整数部分と同様に桁を取得します。

于 2013-03-12T00:34:23.890 に答える