问题描述
我需要读入多项式的系数(浮点数),并按ctrl-d标记结尾。
然后我需要读入x值并显示f(x)。还要以ctrl-d结尾。
I need to read in the coefficients (as floats) of a polynomial and mark the end by ctrl-d.Then I need to read in x values and display f(x). Also ending that with ctrl-d.
到目前为止,我已经使用 scanf
函数进行了尝试。读取系数的效果很好,但是第一次输入ctrl-d后,scanf将不会读取x值。
So far I have tried it with the scanf
function. Reading the coefficients work well but after typing ctrl-d the first time, scanf will not read in x values.
#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);
}
}
推荐答案
Re -在第一次循环后打开 stdin
可能会起作用
Re-opening stdin
may work after the first loop
freopen(NULL, "rb", stdin);
或考虑的想法, clearerr(stdin)
。
不使用 结束输入(关闭 stdin
),使用?
How about instead of using to end input (which closes stdin
), use ?
创建一个函数以读取 float
的 line 。
Create a function to read a line of 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
,处理非数字输入等。
然后需要 float
输入时使用它。
Above still needs some work concerning edges cases: n==0
, when a rare input error occurs, size_t
, handling of non-numeric input, etc.
Then use it whenever float
input is needed.
#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中的浮点数两次。每次以< Ctrl> -d结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!