该函数从标准输入读取多项式的系数并将其存储在给定的数组中。容量参数告诉函数 coeff[] 数组有多少系数空间。该函数尝试读取它可以读取的所有系数,直到到达文件末尾并返回它实际读取的系数数量。如果输入多项式不好(例如,系数太多或输入不能解析为 float ),此函数将打印“无效多项式”并以状态 101 退出程序。
输入文件是这样的:
0.0 6.0
25.00 -47.50 25.17 -5.00 0.33
前两个数字是绘图的范围,第二行表示多项式的系数。
这是我到目前为止的代码:
/**
*/
// Include our own header first
#include "poly.h"
// Then, anything else we need in the implementation file.
#include <stdlib.h>
#include <stdio.h>
/** Exit status if the input polynomail is bad. */
#define INVALID_POLYNOMAIL_STATUS 101
int readPoly( int capacity, double coeff[] )
{
double variable = 0.0;
int ch;
int count = 0;
while ( ( ch = getchar() ) != EOF ) {
for(int i = 0; i < capacity; i++) {
if(scanf("%lf", &variable) != 1) {
fprintf(stderr, "Invalid input");
exit(101);
}
else {
coeff[i] = variable;
count++;
}
}
}
return count;
}
最佳答案
getchar 可能会读取一个值的开头,这是不正确的
一个简单的方法是停止任何错误(EOF 或错误值):
int readPoly( int capacity, double coeff[] )
{
int i;
for(i = 0; i < capacity; i++) {
if (scanf("%lf", &coeff[i]) != 1)
break;
}
return i;
}
另一种方法是手动绕过空格以指示错误:
int readPoly( int capacity, double coeff[] )
{
int i;
for (i = 0; i < capacity; i++) {
for (;;) {
int c;
if ((c = getchar()) == EOF)
return i;
if (!isspace(c)) {
ungetc(c, stdin);
break;
}
if (scanf("%lf", &coeff[i]) != 1) {
fprintf(stderr, "Invalid input");
exit(101);
}
}
return i;
}
注意count与i是多余的,只需i就够了,也可以直接scanf进入数组
关于c - 如何在 C 中读取多项式并将其存储在数组中并进行错误检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723854/