简体   繁体   中英

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. 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

#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.

By the way, the code you wrote shouldn't even compile without a warning on GCC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM