简体   繁体   English

C程序:编写了将int转换为float的代码,但这给了我0.0000,并将我的输入更改为一些奇怪的数字

[英]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.

相关问题 为什么这段代码有效? function 的输入是“string s”,但我们给出的实际输入是“int name”。 C语言 - Why does this code work? The input for the function is "string s" but the actual input we are giving is "int name". C language 编写我的代码以查找模式,但给了我最大的数量 - Wrote my code to look for a mode but gives me the largest number 我写了一个 C 程序来计算数组的标准偏差。 我的代码给出了错误的答案。 我究竟做错了什么? - I wrote a C program to calculate the standard deviation of an array. My code is giving the wrong answer. What am I doing wrong? C程序将浮点数转换为字母等级 - C Program Convert float number to letter grade 浮点数在我的 C 程序中显示不正确 - float number is not displaying correctly in my C program 我的 C 代码给了我很多错误 - My code in C is giving me a lot of errors 我的 C 查找阶乘的程序没有给我想要的结果 - my C program to find factorial is not giving me my desired result 为什么程序没有给我想要的 output? 出了什么问题? - Why is the program not giving me the desired output? What's gone wrong? 向我解释以下C程序的输出 - Explain me the following C program's output 我写的代码是用于输入一个人的日期,这与他的年龄、分数和姓名有关。 但是我无法修复我的代码 - the code i wrote is for input one person's date, which related with his age, score , and name. however I am having trouble to get my code fixed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM