我使用C语言读取未知大小的命令参数,并确定多项式的系数、范围和多项式的次数。我将使用系数重建多项式并对其进行数值分析,但我在读取命令行参数时遇到问题。
例如;
/文件名1.4 2.2 3.3 4.45 5.65 12 14
其中1.4 2.2 3.3 4.45 5.65是多项式的系数,12和14是多项式的范围。
我已经为此挣扎了一段时间,能够实现使用fgets的代码,然后运行for循环来计算字符串中的空间数,以确定多项式的度数和系数的数量,但是这个代码使用了终端,我觉得这是错误的方法。
我确信这与指针有关,但我一直在努力掌握这个概念
我很好奇我需要做的是运行如下的for循环
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define EPSILON 0.01
void main(int argc, char *argv[]){
int i,count;
float a,b,c;
count =0;
for(i=1;i<argc;i++){
if(argc != '\0')
count++;
}
deg = count - 2;
b= argv[count];
a= argv[count -1];
for(i=1;i<=deg;i++){
str[i] = argv[i];
}
}
在这一点上,我几乎是目瞪口呆,任何正确方向的建议都将非常感谢。
最佳答案
你需要一步一步来。
首先明确定义命令行的格式。例如,我们可以说有程序名(argv[0]
)、n
系数和两个数字,约束条件是n > 0
。因此我们有argc > 3
和n = argc - 3
。
代码需要首先检查命令行并将其内容提取到适当类型的变量中。
此时,您不再使用字符串。您可能需要执行其他输入验证。
最后,您可以处理输入。
void usage ()
{
fprintf (stderr, "usage: ...");
exit (EXIT_FAILURE);
}
// do the actual work
void run (double coeff[], int n, double range1, double range2)
{
int deg;
if (n > 1) {
deg = n - 1;
}
else if (coeff[0] != 0) {
deg = 0;
}
else {
// the degree of the 0 polynomial is not defined
...
}
...
}
int main (int argc, char **argv)
{
// Process command line arguments
if (argc <= 3) {
usage ();
}
int n = argc - 3;
// The coefficients are stored from right to left so that
// coeff[i] is the coefficient of x^i
double coeff[n];
double range1, range2;
// FIXME: use strtod instead of atof to detect errors
for (int i = 0; i < n; i++) {
coeff[n - i - 1] = atof (argv[i + 1]);
}
range1 = atof (argv[n + 1]);
range2 = atof (argv[n + 2]);
// At this point you work only with coeff, n, range1 and range2
// Additional input validation
if (range1 >= range2) {
...
}
// do the actual work
run (coeff, n, range1, range2);
return EXIT_SUCCESS;
}
关于c - 读入命令行参数以确定多项式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52595421/