2013-10-17 22 views
0

我試圖使循環看起來就像它預先形成精確的算術,但我不太確定如何打印出我的int(例如115)作爲「假」雙(例1.15)任何幫助,將不勝感激。謝謝!在Java中打印115爲1.15

for(int i = 115; i<350; i+=15) 
{ 
    System.out.print(i); 
    //possibly printf? I'm not very familiar with the method 
}//for 
+0

double num =(double)i/100.0; – AurA

回答

4

你可以用這種簡單的方法做到這一點。

System.out.print(i/100.0); // This will print 1.15, 1.3 

但是如果你想在小數點後打印兩位數字,你需要這樣做。

System.out.printf("%.2f",i/100.0); // This will print 1.15, 1.30 
+0

關閉,但不是我想要的。當通過100.0將第一次轉換爲double時,第四次通過循環時,舍入錯誤變得很好,這意味着它在打印語句中出現。 編輯:刷新,抱歉。感謝您的幫助。 Printf對我來說是一種奇怪的方法.... – MillerR207

0

如何:

for(int i = 115; i<350; i+=15) 
    { 
     System.out.printf("%d.%02d%n", i/100, i % 100); 
    } 
0

由於這可能是關於金錢,我建議使用BigDecimal。不要對貨幣值進行浮點運算,因爲長期來說舍入誤差是不可避免的,儘管它們可能不會出現在這種特殊情況下,使用printf。準確地解決您的問題是:

for (int i = 115; i < 350; i += 15) { 
    System.out.println(new BigDecimal(i).movePointLeft(2)); 
}