[英]C program: Wrote code to convert int to float, but it's giving me 0.0000 and it's changing my input to some strange number
I have the following piece of code, also available at this link . 我有以下代码,也可以在此链接上找到 。
#include <stdio.h>
int main()
{
int n;
printf("\nPlease input an integer to convert to float: %d", n );
scanf("%d", &n);
printf("\nYour float is: %.5f", n);
return(0);
}
What it's doing is not converting the float, it only gives me 0.0000, and it also takes my input and makes it some wacky number. 它所做的是不转换浮点数,它只给我0.0000,它也接受我的输入并使它成为古怪的数字。 I'm not sure what I'm doing wrong, even after looking around on different sites.
我不确定自己在做什么错,即使在不同的站点四处浏览也是如此。 I can't use any library, either, so nothing of atol, etc
我也不能使用任何库,所以atol等都没有
#include <stdio.h>
int main() {
int n;
printf("\nPlease input an integer to convert to float: ");
scanf("%d", &n);
printf("\nYour float is: %.5f", (float)n);
return(0);
}
You have to explicitly write the cast, if you want an integer to be converted to a float in that way. 如果您希望以这种方式将整数转换为浮点数,则必须显式编写转换。 If you don't, this causes undefined behavior.
如果不这样做,则会导致未定义的行为。 Another way is to declare a float variable and assign n to it.
另一种方法是声明一个float变量并为其分配n。
By the way, the code you wrote shouldn't even compile without a warning on GCC. 顺便说一句,您编写的代码在没有GCC警告的情况下也不应编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.