代码之家  ›  专栏  ›  技术社区  ›  KolacheMaster

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

  •  0
  • KolacheMaster  · 技术社区  · 7 年前

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

    ./filename 1.4 2.2 3.3 4.45 5.65 12 14

    其中1.4 2.2 3.3 4.45 5.65是多项式的系数,12和14是多项式的范围。

    我确信这和指针有关,但我一直在努力掌握这个概念

    我很好奇我需要做的是运行一个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];
       }
    
    }
    

    在这一点上我简直目瞪口呆,任何正确方向的建议都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  2
  •   user1157391 user1157391    6 年前

    你需要一步一步来。

    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;
    }