读入命令行参数以确定多项式

Read in command line arguments to determine a polynomial

我正在使用 C 语言读取未知大小的命令参数并确定多项式的系数、它的 运行ge 和多项式的次数。我将使用这些系数来重建多项式并对其进行数值分析,但我在读取命令行参数时遇到了问题。

例如;

./文件名 1.4 2.2 3.3 4.45 5.65 12 14

其中 1.4 2.2 3.3 4.45 5.65 是多项式的系数,12 和 14 是多项式的 运行ge。

我现在一直在努力解决这个问题,并且能够实现利用 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 != '[=10=]')
    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 > 3n = 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;
}