2015-09-11 46 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

我们真的需要另一个答案为这种过度问的问题? –