使用 getchar() 读取浮点数并打印浮点数,它是双精度的

Reading float numbers using getchar() and printing the float number and it's double

我在使用 getchar() 方法将数字转换为浮点数来解决我的问题时遇到了问题。对于我的问题,我需要将字符存储在 fixed size = 50 的数组中。此外,只有在使用 getchar() 读取 space ' ' 或换行符 \n 时才会存储在数组中。这种情况发生直到 EOF 被读取。最后,返回浮点数和它的双精度数(带有制表符 space)并使用 printf.

打印

根据说明,仅允许使用 getchar()。 scanf()fgets()atoi()atol()atof()strtol()strtoul() 等函数或额外的数组不能使用过。

这是我到目前为止的想法。 (请参阅底部的示例输入和输出)

#include <stdio.h>
#define SIZE 50    // assume no more than 50 literals in input
int main(){
 
  float c;
  float u;
  float value = 0.0;
  float resu[SIZE];
  int index = 0;
  int i;
  char sub = '0';

  value = 0;
  c = getchar();
  while ( c != EOF){ 
    if(c == '.'){
      u = 0.1;
    }

    else if (c == ' ' || c == '\n'){ 
      if(u == 0.1){
        value = value * 0.1;
    } 
      resu[index] = value;
      index++;
      value = 0;
    }

    if( c >= '0' && c <= '9'){
        value = value * 10 + (c-sub);
    }
    c = getchar(); // read next
  }
 
  //printing the result
  for(i=0; i < index; i++)
    printf("%.4lf \t %.4lf\n", resu[i],resu[i] *2.0);
 
  return 0;
}

(注意-原始数字和双倍之间有一个制表符)

Sample Input: 
2.3 4.56
43.3 43 5.3
.3 1.2

Sample Output: 
2.3000    4.6000
45.6000    91.2000 //ERROR
43.3000    86.6000
4.3000    8.6000   //ERROR
5.3000    10.6000
0.3000    0.6000
1.2000    2.4000

您不做的两件事是为每个单词初始化 u 或重置 u

float u = 0;
....
    else if (c == ' ' || c == '\n') { 
        if (u == 0.1){
            value = value * 0.1;
        } 
        resu[index] = value;
        index++;
        value = 0;
        u = 0;       // Reset it for next number
    }

此外,您硬编码 u = 0.1,但这仅在只有 1 位小数时有效。对于此作业,这可能没问题,但更好的选择是计算小数点后的数字。

#include <stdbool.h>
#include <math.h>
#include <ctype.h>
...
int digits_after_decimal = 0;
bool have_decimal_point = false;
int value = 0;
int c;
while ((c = getchar()) != EOF) {
    // Decimal point found?
    if ('.' == c) {
        have_decimal_point = true;
    }
    else if (isdigit(c)) {
        // Add this digit to integer value
        // Parentheses not required but added for clarity
        value = (value * 10) + (c - '0');
        // If decimal point already found, increment count
        if (have_decimal_point) digits_after_decimal += 1;
    }
    // Complete word. Save and reset
    // TODO: Multiple spaces between words?
    else if (' ' == c || '\n' == c) {
        // Divide by the correct power of 10 based on
        // the number of digits after the decimal point
        resu[index++] = value / pow(10, digits_after_decimal);
        if (index == SIZE) break;  // Avoid overflow
        // Reset for next number
        digits_after_decimal = 0;
        have_decimal_point = false;
        value = 0;
    }
    // TODO: Negative numbers?
}