1-1-12-12 帮忙看段程序,谢了!
发信人: javarookie (JavaRookie), 信区: Java标题: Re: 帮忙看段程序,谢了!
发信站: BBS 水木清华站 (Fri Nov 15 20:20:32 2002), 转信
【 在 classky (弧度) 的大作中提到: 】
: class Second extends First {
: public static void main(String args[]) {
: methodA((byte)2,1.0);
: }
: static short methodA(byte x, double y){
: return (short)x/y*2;
~~~~~~~~~~~得到的是一个double 值,返回给 short 值时将损失精度
Java 的整数数值运算以 int 为基础
浮点数运算以 double 为基础,换句话说如果运算式中没有显式的cast,
那么加减乘除都是以基础类型进行运算
比如:
byte a = 1;
byte b = 2;
byte c = a + b; // 编译错误
最后的加法中将 a 和 b 转换为 int 计算,所以返回的是 int ,需要显式的声明才
能够返回 byte 值,即:
byte c = (byte)(a+b);
在原例中,(short)x / y * 2 因为其中 y 是 double 型,所以计算以 double 为基
础进行,得到结果是一个 double 型的数值
注意:(short)(x/y*2) 与上式不同,返回一个 short 型(括号的作用)
: }
: }
: 提示有精度损失错误,为什么??
页:
[1]