gpt4 book ai didi

c - C语言中如何将int转为float?

转载 作者:行者123 更新时间:2023-11-30 21:42:05 25 4
gpt4 key购买 nike

我在 C 中有一个简单的问题。如何将 int 值转换为 float,以便我可以向其中添加非整数。

就像说的

int i = 1;

如何将 i 加 0.5 以获得 float 1.5?我试过:

float j = (float)i + 0.5;

似乎不起作用。

请帮忙。

最佳答案

我猜您使用了错误的格式说明符。在 gcc 编译器中,以下程序工作正常。

#include <stdio.h>

int main()
{
int i = 1;
float j = (float)i + 0.5;
printf("%f\n",j);
}

输出:

1.500000

关于c - C语言中如何将int转为float?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42829497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com