我需要一种方法在 C 中两次读取浮点数。每次以 <Ctrl>-d 结尾



我需要读取多项式的系数(作为浮子(,然后按ctrl-d标记结束。然后,我需要阅读x值并显示f(x(。还以Ctrl-D结束了这一点。

到目前为止,我已经使用scanf函数尝试了它。读取系数效果很好,但是在第一次键入ctrl-d之后,scanf将不会读取x值。

#include <stdio.h>

int main(){
    int count = 0;
    float poly[33];
    while(scanf("%f", &poly[count]) != EOF){   // reading the coeffs
        count++;
    }
    printf("Bitte Stellen zur Auswertung angebenn");
    float x;
    float res;
    while(scanf("%f", &x) != EOF){   //Here it Fails. Since scanf still sees the EOF from before
        res = 0;
        for(int i = 1; i < count; i++){
            res += poly[i-1] * x + poly[i];
        }
        printf("Wert des Polynoms an der Stelle %f: %fn", x, res);
    }
}

重新打开stdin可能在第一个循环之后工作

freopen(NULL, "rb", stdin);

或考虑@Jonathan Leffler clearerr(stdin)的想法。


如何而不是使用 ctrl d 来结束输入(关闭stdin(,使用 enter enter

创建一个函数以读取float line

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
int read_rest_of_line(FILE *stream) {
  int ch;
  do {
    ch = fgetc(stream);
  } while (ch != 'n' && ch != EOF);
  return ch;
}
// Read a line of input of float`s.  Return count
int read_line_of_floats(float *x, int n) {
  bool char_found = false;
  int count;
  for (count = 0; count < n; count++) {
    // Consume leading white-space looking for n - do not let "%f" do it
    int ch;
    while (isspace((ch = getchar()))) {
      char_found = true;
      if (ch == 'n') {
        return count;
      }
    }
    if (ch == EOF) {
      return (count || char_found) ? count : EOF;
    }
    ungetc(ch, stdin);
    if (scanf("%f", &x[count]) != 1) {
      read_rest_of_line(stdin);
      return count;
    }
  }
  read_rest_of_line(stdin);
  return count;
}

上面仍然需要一些有关边缘情况的工作:n==0,当发生罕见输入错误时,size_t,非数字输入的处理等。
然后在需要float输入时使用它。

#define FN 33
int main(void) {
  float poly[FN];
  int count = read_line_of_floats(poly, FN);
  // Please specify positions for evaluation
  printf("Bitte Stellen zur Auswertung angebenn");
  float x;
  float res;
  while (read_line_of_floats(&x, 1) == 1) {
    res = 0;
    for (int i = 1; i < count; i++) {
      res += poly[i - 1] * x + poly[i];
    }
    // Value of the polynomial at the location
    printf("Wert des Polynoms an der Stelle %f: %fn", x, res);
  }
}

相关内容

最新更新