C语言之类型转换

#include <stdio.h>

// 类型转换

int main()
{
    //*****************强制类型转换之自动转换*****************
    // 1、参加运算的成员全部变为int类型参加运算的,结果也是int类型的
    printf("%d\n", 5/2);

    // 2、当表达式中出现了带小数的实数,参加运算的成员全部变为double类型,结果也变为double类型
    printf("%f\n", 5.0/2);

    // 3、当表达式中有有符号数,也有无符号数,参加运算的成员变成无符号数参加运算,结果也是无符号数
    int a = -8;
    unsigned int b = 7;
    if(a+b > 0)
    {
        printf("a+b>0\n");
    }
    else
    {
        printf("a+b<0\n");
    }

    // 4、在赋值语句中,等号右边的类型自动转换位等号左边的类型
    int c;
    float d = 5.8f; // 5.8后面加f代表5.8是float类型,不加的话,认为是double类型
    c = d;
    printf("c = %d\n", c);
    printf("d = %f\n", d);

    // 5、强制类型转换
    int x = 10;
    int y = 4;
    float w;
    w = x / y;   // 先运算10/4,结果为2      然后转换为float类型,为2.000000
    printf("w = %f\n", w);
    w = (float)x / (float)y;
    printf("w = %f\n", w);

    return 0;
}

执行结果如下:

猜你喜欢

转载自blog.csdn.net/weixin_40379143/article/details/108430904