当前位置: 技术问答>java相关
请教在这个程序里的变量类型为什么用float而不用short
来源: 互联网 发布时间:2015-11-19
本文导语: total是个整数,我觉得用short就可以,但答案是用的float,用什么好处吗?用short不可以吗?初学者,还请多多帮助,谢谢了! class Invest { public static void main(String[] arguments) { float total = 14000; ...
total是个整数,我觉得用short就可以,但答案是用的float,用什么好处吗?用short不可以吗?初学者,还请多多帮助,谢谢了!
class Invest {
public static void main(String[] arguments) {
float total = 14000;
System.out.println("Original investment: $" + total);
// Inceases by 40 percent the first year
total = total + (total * .4F);
System.out.println("After one year: $" + total);
// Loses $1,500 the second year
total = total - 1500F;
System.out.println("After two years: $" + total);
// Increases by 12 percent the third year
total = total + (total * .12F);
System.out.println("After three years: $" + total);
}
}
class Invest {
public static void main(String[] arguments) {
float total = 14000;
System.out.println("Original investment: $" + total);
// Inceases by 40 percent the first year
total = total + (total * .4F);
System.out.println("After one year: $" + total);
// Loses $1,500 the second year
total = total - 1500F;
System.out.println("After two years: $" + total);
// Increases by 12 percent the third year
total = total + (total * .12F);
System.out.println("After three years: $" + total);
}
}
|
total * .4F 自动转换为float 所以不行。
|
不管total是short还是float,total * .4F一定会是float,所以用float就不用转来转去了。