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

恩兹德

我在使用getchar()方法将数字转换为float时遇到麻烦,无法解决我的问题。对于我的问题,我需要将字符存储在的数组中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
约翰尼·莫普(Johnny Mopp)

您不需要做的两件事是为每个单词初始化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?
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章