我需要读入多项式的系数(作为 float )并用 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 angeben\n");
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: %f\n", x, res);
}
}
最佳答案
重新打开 stdin
可能会在第一次循环后起作用
freopen(NULL, "rb", stdin);
或者考虑 @Jonathan Leffler clearerr(stdin)
的想法。
如何不使用 Ctrld 结束输入(关闭 stdin
),而是使用 Enter?
创建一个函数来读取float
的行。
#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
,处理非数字输入等。< br/>
然后在需要 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 angeben\n");
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: %f\n", x, res);
}
}
关于c - 我需要一种在 C 中两次读取 float 的方法。每次都以 <Ctrl>-d 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56307136/