【问题标题】:Converting a variable user input float into an array of characters in C?将变量用户输入浮点数转换为C中的字符数组?
【发布时间】:2017-11-11 01:07:22
【问题描述】:

我在程序中的目标是提示用户输入一定范围内的货币价值(浮动)以用于另一个功能。但是,使用字符数组作为输入来完成另一个功能似乎要容易得多。我已经研究过使用 sprintf 和 snprintf,但不确定如何/是否可以使用变量输入而不是常量来实现这些。

这个数字将被传递给的函数需要将数字转换为书面文字。示例:1150.50 = 一千一百五十美元五十美分。

这是我要实现的代码段;

do {

        puts("Please enter the amount of the paycheck, this must be from 0$ to 10000$:  \n");
        scanf("%.2f", entered_amount);

        if (entered_amount < 0.00 && entered_amount > 10000.00) {
        printf("This is not a valid amount, please try again!   \n\n");

        }

    } while (entered_amount < 0.00 && entered_amount > 10000.00);

    sprintf(amount, "%f", entered_amount);                  
    //Trying to convert a float entered by the user to an array of characters to use in the number_to_word function!
    printf("%s", amount);

entered_amount 是用户输入的浮点数,amount 是 字符数组。前任: 5555.55 = {"5,5,5,5,.,5,5"}

感谢所有帮助和反馈,谢谢!

【问题讨论】:

  • 1) entered_amount &lt; 0.00 &amp;&amp; entered_amount &gt; 10000.00) --> entered_amount &lt; 0.00 || entered_amount &gt; 10000.00)
  • 啊,很好,谢谢!
  • scanf("%.2f", entered_amount);...emmm..在某处缺少&amp;
  • 当第一次输入负数然后输入不是数字时,这个(带有建议的修复)永远循环。

标签: c string printf double


【解决方案1】:

如果amount 是足够大小的char 数组,那么在调用sprintf 之后,你就有了你想要的结构。

sprintf(amount, "%f", entered_amount);

您可以通过printf 轻松打印。

printf("%s", amount);   //Print entire array
//Print char by char
size_t i = 0;
for (i = 0; i < strlen(amount); i++)
    printf("%c", amount[i]);

问题更多在于您的 if 语句检查范围。

if (entered_amount < 0.00 && entered_amount > 10000.00) {

这永远不会被执行。改用这个:

if (entered_amount < 0.00 || entered_amount > 10000.00) {

读取float时,应该通过指针来读取(检查附加的&字符):

scanf("%.2f", &entered_amount);

【讨论】:

  • 嗯,我修复了 ||而不是 && 在 while 循环中,以及 &entered_amount。真正的问题是 sprintf(amount, "%f", enter_amount);,当我 printf("%s", amount) 它只打印 0.00000..不管输入的值是多少。
猜你喜欢
  • 1970-01-01
  • 2019-04-01
  • 2017-09-28
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多