zoukankan      html  css  js  c++  java
  • 04 基本数据类型转换

    1,自动类型转换

      ①在C程序在进行赋值或者运算时,精度小的类型自动转换为精度大的数据类型,这个就是自动类型转换。

      ②数据类型按精度(容量)大小排序为:

      

       

      ③数据类型自动转换规则

        

       ④

     1 #include<stdio.h>
     2 
     3 void main() {
     4     char c1 = 'a';
     5     int num1 = c1; //ok char精度小于int精度
     6     double d1 = num1;//ok int精度小于double 
     7     printf("c1=%c num1=%d d1=%f
    ", c1, num1, d1);
     8 
     9     short s1 = 10;
    10     int num2 = 20;
    11     int num3 = s1 + num2;//ok
    12     printf("s1=%d num2=%d num3=%d
    ", s1, num2, num3);
    13 
    14     float f1 = 1.1f;//ok
    15     double d2 = 4.58667435;
    16     f1 = d2;  // 出现精度丢失(double->float>  warning : 从“double”转换到“float”,可能丢失数据
    17     printf("f1=%f d2=%f
    ", f1,d2);
    18 }

       ⑤自动类型转换细节说明

        有多种自动类型的数据混合运算时,系统首先自动将所有数据转换成精度最大的那种数据类型,然后再进行计算(如int型和short型运算时,先把short转成int型后进行运算)

        若两种类型的字节数不同,转换成字节数大的类型,若两种类型的字节数相同,且一种有符号,一种无符号,则转换成无符号类型

        在赋值运算中,赋值号两边的数据类型不同时,赋值号右边的类型将转换成左边的类型,如果右边变量的数据类型长度比左边长时,将丢失一部分数据,这样会降低精度,丢失的部分按四舍五入向前舍入

    2,强制类型转换

      ①将精度高的数据类型转换成精度小的数据类型,使用时要加上强制转换符(),但可能造成精度降低或溢出,格外要注意。

      ②强制类型转换一般格式如下:

        (类型名)表达式

          表达式:任何有值的都可以称为表达式,比如 1+2 , int num=2

      ③这种强制类型转换操作并不改变操作数本身

     1 #include<stdio.h>
     2 
     3 void main() {
     4     double d1 = 1.934;
     5     int num = (int)d1; //这里注意,不是四舍五入,而是直接截断小数后的部分
     6     printf("num=%d d1=%f
    ", num, d1);
     7 
     8 
     9     //强制类型转换只对最近的数有效,如果希望针对更多的表达式转换,使用()
    10     int num2 = (int)3.5 * 10 + 6 * 1.5;  // 30+9.0=39.0->39 warning:从“double”转换到“int”,可能丢失数据
    11     int num3 = (int)(3.5 * 10 + 6 * 1.5); //35.0+9.0=44.0->44
    12     printf("num2=%d num3=%d
    ", num2, num3);
    13 
    14 
    15 }

       ④强制类型转换细节说明

        当进行数据的从精度高 -- 》 精度低,就需要使用到强制转换

        强制转换只针对于最近的操作数有效,往往会使用小括号提升优先级

      

        

          

      

  • 相关阅读:
    最大子数组问题(分治策略实现)
    Solving the Detached Many-to-Many Problem with the Entity Framework
    Working With Entity Framework Detached Objects
    Attaching detached POCO to EF DbContext
    如何获取qq空间最近访问人列表
    Health Monitoring in ASP.NET 2.0
    problem with displaying the markers on Google maps
    WebMatrix Database.Open… Close() and Dispose()
    Accessing and Updating Data in ASP.NET: Retrieving XML Data with XmlDataSource Control
    Create web setup project that has crystal reports and sql script run manually on client system
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/12337460.html
Copyright © 2011-2022 走看看