zoukankan      html  css  js  c++  java
  • 类型转化方法

    1、隐式转化

    隐式转化规则:由低到高依次是 int--->long---->long long--->float--->double

                             若运算中有char short 则一并转化为int

     1 #include <stdio.h>
     2 
     3 int main()
     4 {
     5     char a; short b; int c;
     6     long long d; float e; double f;
     7 
     8     printf("sizeof(a)=%d
    ",sizeof(a));//a占1个字节长度
     9     printf("sizeof(b)=%d
    ",sizeof(b));//b占2个字节长度
    10     printf("sizeof(c)=%d
    ",sizeof(c));//c占4个字节长度
    11 
    12     printf("========================
    ");
    13 
    14     printf("sizeof(a+b)=%d
    ",sizeof(a+b));//a+b占4个字节长度
    15     printf("sizeof(a+c)=%d
    ",sizeof(a+c));//a+c占4个字节长度
    16     printf("sizeof(b+c)=%d
    ",sizeof(b+c));//b+c占4个字节长度
    17 
    18     printf("========================
    ");
    19 
    20     printf("sizeof(d)=%d
    ",sizeof(d));//long long型占8个字节长度
    21     printf("sizeof(a+d)=%d
    ",sizeof(a+d));//char型和long long型一起运算,则提升到long long型,占8个字节长度
    22 
    23     printf("========================
    ");
    24 
    25     c=3; e=5.6;
    26     printf("%f
    ",c+e);//int型和float型一起运算,则提升到float型,占4个字节,小数点后保留6位数
    27     e=10.0;
    28     printf("%f
    ",e/c);//int型和float型一起运算,则提升到float型,占4个字节,小数点后保留6位数
    29 
    30     printf("========================
    ");
    31 
    32     printf("sizeof(a)=%d
    ",sizeof(a));
    33     printf("sizeof(f)=%d
    ",sizeof(f));//double型占8个字节
    34 
    35     printf("========================
    ");
    36 
    37     printf("sizeof(d+e)=%d
    ",sizeof(d+e));//long long型和float一起运算,则变成float型,占4个字节
    38     printf("sizeof(a+f)=%d
    ",sizeof(a+f));//char型和double型一起运算,则提升到double型,占8个字节
    39 
    40 
    41     return 0;
    42 }

    打印结果:

    2、强制转化

    格式:( 类型)待转表达式

     1 #include <stdio.h>
     2 
     3 int main()
     4 {
     5     int a=3; int b=10;
     6     float c=b/a;
     7     printf("%f
    ",c);//结果是3.000000
     8 
     9     //若我们想得到3.333333的结果的时候
    10 
    11     float d=(float)b/a;//将b从int型转化到float型,则运算结果以float型的小数表示
    12     printf("%f
    ",d);
    13 
    14     return 0;
    15 }

    打印结果:

    3、浮点数跟0值比较

     1 #include <stdio.h>
     2 
     3 int main()
     4 {
     5     double tmp=0.0;
     6     if(tmp>-0.000001 && tmp<+0.000001)//与-0.000001和+0.000001比较大小
     7     {
     8         printf("tep==0
    ");
     9     }
    10     else
    11         printf("tep!=0
    ");
    12 
    13     return 0;
    14 }

    打印结果:

  • 相关阅读:
    BZOJ2821 作诗(Poetize) 【分块】
    BZOJ2724 蒲公英 【分块】
    Codeforces 17E Palisection 【Manacher】
    BZOJ2565 最长双回文串 【Manacher】
    Codeforces 25E Test 【Hash】
    CODEVS3013 单词背诵 【Hash】【MAP】
    HDU2825 Wireless Password 【AC自动机】【状压DP】
    HDU2896 病毒侵袭 【AC自动机】
    HDU3065 病毒侵袭持续中【AC自动机】
    HDU2222 Keywords Search 【AC自动机】
  • 原文地址:https://www.cnblogs.com/onemusk/p/9481986.html
Copyright © 2011-2022 走看看