2015-09-11 121 views
-2

爲什麼平均不出來雙倍?

/** 
 
* Write a description of class GUI here. 
 
* 
 
* @author (your name) 
 
* @version (a version number or a date) 
 
*/ 
 

 
import java.util.*; 
 
public class GUI 
 
{ 
 
    // instance variables - replace the example below with your own 
 
    public static void main(String [] args){ 
 
     
 
     Scanner r = new Scanner(System.in); 
 
     
 
     int x; 
 
     int y; 
 
     int z; 
 
     
 
     System.out.println("x"); 
 
     
 
     x = r.nextInt(); 
 
     
 
     System.out.println("y"); 
 
     
 
     y = r.nextInt(); 
 
     
 
     System.out.println("z"); 
 
     
 
     z = r.nextInt(); 
 
     
 
     double t = (x+y+z)/3; 
 
     
 
     System.out.println("result " + t); 
 
    } 
 
}

你好,以上是我的代碼。

我故意把它做成int x,y,z來測試程序。

當我輸入例如(當運行程序時):$ x = 1,1,3 $它總是回答答案!爲什麼是這樣?

+6

整數除法 – Reimeus

+0

因爲你轉換爲加倍您的最終結果, – user902383

+0

'INT/INT = int'但是'(雙)INT/INT = double' –

回答

2

這是一個Java的整數除法的例子,它必須總是返回另一個整數。它截斷任何十進制結果。即使結果分配給double,也會發生這種情況。

使用一個double文字劃分強制浮點除法。

double t = (x+y+z)/3.0; 
+5

我們真的需要另一個答案爲這種過度問的問題? –