本文介绍了java中的字节类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序让我失去了精度误差,但由于数字很小,我无法想到任何精度损失

the program gives me loss of precision error but i cant think of any precision loss since numbers are small

 class Demo  
 {  
   public static void main(String args[])  
   {  
      byte b1=3;  
      byte b2=2;  
      byte b3=b1+b2;  
      System.out.println(b3);  
   }  
 }


推荐答案

附加表达式 b1 + b2 的类型为 int - 没有在小于<$的较小类型上定义任何加法运算符C $ C> INT 。因此,为了将其转换回字节,您必须进行投射:

The addition expression b1 + b2 is of type int - there aren't any addition operators defined on smaller types than int. So in order to convert that back to a byte, you have to cast:

byte b3 = (byte) (b1 + b2);

请注意,虽然碰巧知道价值很小,但是编译器并不关心你在前两行中设置的值 - 它们可能都知道它们都是100。同样,虽然知道 int 你试图分配给字节变量只是将两个 byte 值相加(或者更确切地说,两个值从 byte 提升到<$ c $)的结果c> int ),整个表达式只是 int ,并且就语言而言可能来自任何地方。

Note that although you happen to know that the values are small, the compiler doesn't care about the values you've set in the previous two lines - they could both be 100 for all it knows. Likewise although you know that the int you're trying to assign to a byte variable is only the result of adding two byte values together (or rather, two values promoted from byte to int), the expression as a whole is just int and could have come from anywhere as far as the language is concerned.

(添加可以溢出的事实是一个单独的事情,但这将是一个不一致的参数 - 毕竟,你可以添加两个 int 值一起并将结果存储在 int 变量中,即使添加可能很容易溢出。)

(The fact that the addition can overflow is a separate matter, but that would be an inconsistent argument - after all, you can add two int values together and store the result in an int variable, even though the addition could have overflowed easily.)

这篇关于java中的字节类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 02:25