运行C程序的命令行参数

5
#include<stdio.h>
#include<math.h>

int main(int argc, char **argv){

    // read in the command-line argument
    double x,c;
    double epsilon = 1e-15;    // relative error tolerance
    double t ; // estimate of the square root of c
    //scanf("%lf",&t);
    t=**argv-'0';
    printf("%lf ",t);
    c=t;
    // repeatedly apply Newton update step until desired precision is achieved
    while (fabs(t - c/t) > epsilon*t) {
        t = (c/t + t) / 2.0;
    }
    // print out the estimate of the square root of c
    printf("%lf",t);

    return 0;
}

在这个程序中,我想要使用命令行参数运行。我该如何做到这一点?

1
你的程序中 x 是用来做什么的? - Mr Lister
谢谢大家回答我的问题。我已经得到了答案。 - Moshi
6个回答

4
为了从终端运行命令行参数,您需要使用以下语法:

在终端中执行命令行参数,需要使用以下语法:

gcc filename.c

./a.out "your argument her without quotation mark"

2

命令行参数的数量存储在argc中。每个参数都存储在argv[0]argv[1]等中。通常,argv[0]包含可执行文件的名称。


2

打开一个终端(命令行)并输入 "gcc nameOfFile.c argument1 argument2",但不要输入引号。你输入的每个参数都将传递给程序,并可以通过 argv[0]、argv[1] 等访问。


我用nameOfFile.exe 0 2来执行,但它不起作用。它总是给出结果67.000000 8.185353。 - Moshi

2

不要使用操作标准输入的scanf,而应该使用操作字符串的sscanf
所以正确的写法是:

sscanf(argv[1], "%lf", &t);

扫描第一个命令行参数。


2

看起来你想向程序传递一个double值。但是你正在使用**argv从命令行检索传递的double值。但是**argv实际上是单个字符。

你需要做的是使用atof()将字符串转换为double。

t = atof(argv[1]); // argv[1] is the 1st parameter passed.

另一个潜在的问题在于这里:fabs(t - c/t) 如果t变为0,你可能会遇到除以零的情况。


1

1) 你需要使用argc(命令行参数的数量)和argv[](参数本身)。

2) 在访问命令行变量之前,检查argc总是一个好主意(即确保您实际上已经获得了命令行参数,然后再尝试使用它)。

3) 有几种方法可以将命令行参数(字符串)转换为实数。一般来说,我更喜欢使用“sscanf()”。

以下是一个示例:

#include<stdio.h>
#include<math.h>

int main(int argc, char **argv){

    double x,c;
    double epsilon = 1e-15;    // relative error tolerance
    double t ; // estimate of the square root of c

    //scanf("%lf",&t);
    if (argc != 2) {
      printf ("USAGE: enter \"t\"\n")l
      return 1;
    } 
    else  if (sscanf (argv[1], "%lf", &t) != 1) {
      printf ("Illegal value for \"t\": %s\n", argv[1]);
      return 1;
    }

    printf("%lf ",t);
    c=t;
    // repeatedly apply Newton update step until desired precision is achieved
    while (fabs(t - c/t) > epsilon*t) {
        t = (c/t + t) / 2.0;
    }
    // print out the estimate of the square root of c
    printf("%lf",t);

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接