2014-02-21 36 views
0

我的代码:在控制台司两个静态整数总是返回0%的比例

public class Test { 

public static int l = 29; 
public static int w = 16; 
public static int total = w + l; 
public static int result = w/total; 
public static int Result = total * 100; 

public static void main(String[] args) { 

     System.out.println("You're W/L ratio is: " + (Result) + "%"); // Display the string. 
} 
} 

响应:你是W/L比为:0%

回答

1

通过铸造wtotaldouble来进行计算,或者只是让它们以double开头。对于第一种选择:

public static double result = (double)w/(double)total; 
2

你做的INT除法它总是返回一个int,所以w/total将始终为0,因为total总是大于w。首先乘以100。

int result = (w * 100)/total; 

你也想学习和使用java的命名规则。变量名称应以小写字母开头。

1

每当你做除法时这两个数字都是整数,在结果你会得到回报的整数。

这实际上意味着您将获得(a/b)的底价值;即:

1/2 = 0作为1/2 => 0.5> 0.5 = 0的层;

3/4 = 0 as 3/4 => 0.75> floor = 0.75 = 0;

etc