C语言类型转换

类型转换允许我们将一种数据类型转换为其他数据类型,在C语言中,我们使用由(type)来表示类型转换的操作符。

语法

(type)value;

注意:始终建议将较低的值转换为较高值以避免数据丢失。

无类型转换:

int f= 9/4;  
printf("f : %d\n", f );//Output: 2

使用类型转换:

float f=(float) 9/4;  
printf("f : %f\n", f );//Output: 2.250000

类型转换示例

下面来看看一个简单的例子,如何将int值转换成float。创建一个源文件:type-cast.c,其代码如下所示 -

#include <stdio.h>      

void main() {

    float f = (float)9 / 4;
    printf("f : %f\n", f);

}

执行上面查询语句,得到以下结果 -

f : 2.250000

上一篇: C语言goto语句 下一篇: C语言函数