Java數據類型

Debug the code on page 35——locate the bugs and fix the bugs.

一 Java數據類型轉換規則

  1. If either of the operands is of type double, the other one will be
    converted to a double.
  2. Ohterwise, if either of the operands is of type float, the other one will
    be converted to a float.
  3. Ohterwise, if either of the operands is of type long, the other one will
    be converted to a long.
  4. Ohterwise, both operands will be converted to an int.

二 Debug the code on page 35——locate the bugs and fix the bugs.


根據編譯結果對錯誤代碼進行了修改,編譯運行均通過

class AutoCast 
{   
    /**
    *對於整數常量默認是int型 浮點型常量默認爲double型
    *byte   範圍 -2^7 -- 2^7-1            8-bit
    *short  範圍 -2^15 -- 2^15-1          16-bit
    *int    範圍 -2^31 -- 2^31-1          32-bit
    *long   範圍 -2^63 -- 2^63-1          64-bit
    *char   範圍 0-65535(0 -- 2^16-1)     16-bit
    *float  精度 小數部分佔7位              32-bit
    *double 精度 小數部分佔15位             64-bit
    */
    public static void main(String[] args) 
    {
        AutoCast.cast();
    }
    public static void cast() {
        int i,j;
        //編譯錯誤2:常量0.1默認是double型 超過float型的最大範圍
        //float f1 = 0.1;
        //改正如下:
        float f1 = 0.1F;
        float f2 = 123;
        long l1 = 12345678;
        //編譯錯誤1:8888888888超過long型整數的最大範圍
        //long l2=8888888888;
        //改正如下:
        long l2=88888888;
        double d1 = 2e20;
        double d2=124;
        //注意:雖然整型常量1 2 默認是int型,
        //但未1和2未超過byte範圍,下面兩條語句編譯時並不報錯
        //但byte b = b1-b2;編譯出錯
        byte b1 = 1;
        byte b2 = 2;
        //編譯錯誤3:byte型能表示的最大範圍是127
        //byte b3 = 129;

        //編譯錯誤8:局部變量未初始化就使用
        //改正如下:爲局部變量i,j賦初值0;
        i=0;
        j=0;
        j = j+10;
        i = i/10;
        //編譯錯誤4:常量0.1默認是double型,i*0.1運算時i的值也轉換爲double
        //i*0.1運算結果爲double,java不會自動將double轉爲int,可以強制轉換,但損失精度
        //i = i*0.1;
        //改正如下:
        i = (int)(i*0.1);
        char c1 = 'a';
        //注意:雖然整型常量125默認是int型,
        //但未125未超過byte範圍,下面一條語句編譯時並不報錯
        //但char c = c1+c2;編譯出錯
        char c2 = 125;
        //編譯錯誤5:b1-b2的結果變爲int型,java不會自動將int轉爲byte
        //byte b = b1-b2;
        //改正如下:強制類型轉換,有可能損失精度
        byte b = (byte)(b1-b2);
        //編譯錯誤6:整型常量1默認是int型,運算時c1和c2的值提升爲int型,
        //運算結果爲int型,java不會自動將int轉爲char,可以強制轉換,但可能損失精度
        //char c = c1+c2-1;
        char c = (char)(c1+c2-1);
        float f3 = f1+f2;
        //編譯錯誤7:浮點型常量0.1默認是double類型
        //float f4 = f1+f2*0.1;
        //改正如下:強制類型轉換,有可能損失精度
        float f4 = (float)(f1+f2*0.1);
        double d = d1*i+j;
        float f = (float)(d1*5+d2);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章