zoukankan      html  css  js  c++  java
  • 表达式的类型转换

    一段小程序来解释表达式中的各个数据类型的转换机制。

    package com.liaojianya.chapter1;
    /**
     * This program demonstrates the convertion of data type.
     * @author LIAO JIANYA
     *
     */
    public class TypeConvert6_17
    {
    	public static void main(String[] args)
    	{
    		char ch = 'a';
    		short a = -2;
    		int b = 3;
    		float f = 5.3f;
    		double d = 6.28;
    
    		System.out.println("ch / a = " + ch / a);
    		System.out.println("the type of (ch / a) is :  " + getType((ch / a)));
    		
    		System.out.println("d / f = " + d / f);
    		System.out.println("the type of (d / f) is :  " + getType((d / f)));
    		
    		System.out.println("a + b = " + (a + b));
    		System.out.println("the type of (a + b) is :  " + getType((a + b)));
    		
    		System.out.println("(ch / a) - (d / f) - (a + b) = " + ((ch / a) - (d / f) - (a + b)));		
    		System.out.println("the type of ((ch / a) - (d / f) - (a + b)) is :  " 
    		+ getType(((ch / a) - (d / f) - (a + b))));
    	}
    		public static String getType(Object o)
    		{
    			return o.getClass().toString();
    		}
    		public static String getType(int o)
    		{
    			return "int";
    		}
    		public static String getType(char o)
    		{
    			return "char";
    		}
    		public static String getType(short o)
    		{
    			return "short";
    		}
    		public static String getType(float o)
    		{
    			return "short";
    		}
    		public static String getType(double o)
    		{
    			return "double";
    		}
    
    }
    

      运行结果:

    ch / a = -48
    the type of (ch / a) is :  int
    d / f = 1.1849056177353188
    the type of (d / f) is :  double
    a + b = 1
    the type of (a + b) is :  int
    (ch / a) - (d / f) - (a + b) = -50.18490561773532
    the type of ((ch / a) - (d / f) - (a + b)) is :  double
    

     分析:

     1)占用字节较少的数据类型转换成占用字节较多的数据类型。

     2)字符类型会转换成int类型。

     3)int类型会转换成float类型。

     4)表达式中出现double,则其他操作数也会转换成double类型。

     5)总结:大鱼吃小鱼:占字节多的替换占字节少的;精度高的优先;优先级排序:byte,short,int,long,float,double。

  • 相关阅读:
    diary and html 文本颜色编辑,行距和其它编辑总汇
    bash coding to changeNames
    virtualbox ubuntu 网络连接 以及 连接 secureCRT
    linux 学习6 软件包安装
    linux 学习8 权限管理
    vim 使用2 转载 为了打开方便
    ubuntu
    linux 学习15 16 启动管理,备份和恢复
    linux 学习 14 日志管理
    linux 学习 13 系统管理
  • 原文地址:https://www.cnblogs.com/Andya/p/5680044.html
Copyright © 2011-2022 走看看