2011-07-28 30 views
2

我正在製作一個程序,將一個大數字變成一個字符串,然後添加該字符串的字符。它工作正常,我唯一的問題是,它不是將它作爲一個正常的數字,而是將Java轉換爲標準形式,這使得解析字符串變得困難。有沒有解決這個問題的方法?任何方式來避免包含結果「9.223372036854776E18」

public static void main(String ags[]) { 
    long nq = (long) Math.pow(2l, 1000l); 
    long result = 0; 
    String tempQuestion = Double.toString(nq); 
    System.out.println(tempQuestion); 
    String question = tempQuestion.substring(0, tempQuestion.length() - 2); 
    for (int count = 0; count < question.length(); count++) { 
     String stringResult = question.substring(count, count + 1); 
     result += Double.parseDouble(stringResult); 
    } 
    System.out.println(result); 
+0

你的代碼是什麼? –

+0

你的情況是什麼將是一個'正常'的數字? –

回答

1

其他答案是正確的,你可以使用java.text.NumberFormatJavaDoc)來設置你的輸出格式。使用printf也是格式化的選項,類似於NumberFormat。但我在這裏看到別的東西。它看起來像你混了你的數據類型:在

nq = (long) Math.pow(2l, 1000l);

您已經截斷雙倍返還值從數學到長。那麼你應該使用long作爲數據類型而不是double進行轉換。所以使用Long.toString(long),這不會添加任何指數輸出。

使用Long.toString(nq)而不是Double.toString(nq);在你的代碼中。

1

正如你所說:「NumberFormat」。班上。

0

鏈接的Javadoc的NumberFormat:

1

的BigInteger是很容易使用,你不要用它精確的風險問題。 (在這種特定情況下,我不認爲這是一個精密的問題,因爲Math.pow(2, 1001) % 100000返回正確的最後5位數字,但對於更大的數字最終你會丟失信息。)這裏是你如何使用的BigInteger:

groovy:000> b = new BigInteger(2L) 
===> 2 
groovy:000> b = b.pow(1001) 
===> 214301721437253464189685009812000362112280962341106721488750077674070210224 
98722449863967576313917162551893458351062936503742905713846280871969155149397149 
60786913554964846197084214921012474228375590836430609294996716388253479753511833 
1087892154125829142392955373084335320859663305248773674411336138752 
groovy:000> ((b + "").toList().collect {new Integer(it)}).inject(0) {sum, n -> sum + n} 
===> 1319 

以下是一個Java同樣的事情:

public class Example 
{ 
    public static void main(String[] args) 
    { 
    int sum = 0; 
    for (char ch : new java.math.BigInteger("2").pow(1001).toString().toCharArray()) { 
     sum += Character.digit(ch, 10); 
    } 
    System.out.println(sum); 
    } 
} 
0

只需更換最後一行:

System.out.println(result); 

System.out.printf("%d", result); 
相關問題