简体   繁体   English

浮点数到C,sprintf中的char数组

[英]float to char array in C, sprintf

I've been googling but I haven't found a simple float to char using the sprintf function. 我一直在谷歌上搜索,但我还没有找到一个使用sprintf函数的简单浮点数。 So far - this is all I've written in my small code section. 到目前为止 - 这是我在我的小代码部分写的所有内容。 The problem is that I always get a 0 return. 问题是我总是得到0回报。

   int main()
   {
        float num_input[9];
        printf("Enter a real number: ");
        scanf("%f", &num_input);
        printf("%f", num_input);
        char str_num[9];
        sprintf(str_num, "%f", &num_input);
        printf(str_num);

        return 0;
    }

Thank you to everyone that helped! 谢谢所有帮助过的人! I finally saw what I did wrong and learnt more. 我终于看到了我做错了什么,学到了更多。 The final code written was: 最终编写的代码是:

float num_input[9];
printf("Enter a real number: ");
scanf("%f", &num_input);
char str_num[9];
int index = 0;
sprintf(str_num, "%f", num_input[index]);

sprintf(str_num, "%f", &num_input); is wrong. 是错的。 You should use something like: 你应该使用类似的东西:

sprintf(str_num, "%f", num_input[index]);  /* 0 <= index < 9 */
/*                    ^          ^^^^^  */

After this keep the fingers crossed that str_num doesn't overflow. 在此之后保持手指交叉, str_num不会溢出。

Remember that "%f" specifier of printf family of function should have a matching double or float ( float becomes double after default argument promotion). 请记住, printf系列的"%f"说明符应该具有匹配的doublefloat (默认参数提升后float变为double )。


Perhaps you should make the similar fix for scanf and printf also: 也许您应该对scanfprintf进行类似的修复:

scanf("%f", &num_input[0]);
printf("%f", num_input[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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