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

问题描述

我无法使用 getchar() 方法将数字转换为浮点数来解决我的问题。对于我的问题,我需要将字符存储在 fixed size = 50 的数组中。此外,只有在使用 getchar() 读取空格 ' ' 或换行符 \n 时才会存储在数组中。这种情况会一直持续到 EOF 被读取。最后,使用 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?
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...