簡體   English   中英

命令行參數來運行ac程序

[英]command line argument to run a c program

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

在這個程序中,我想用命令行參數運行。 我怎樣才能做到這一點?

命令行參數的數量在argc 每個參數都在argv[0]argv[1]等中。傳統上, argv[0]包含可執行文件的名稱。

打開一個終端(命令行)並輸入“gcc nameOfFile.c argument1 argument2”不要輸入引號。 您鍵入的每個參數都將傳遞給您的程序,並可由argv [0],argv [1]等訪問

而不是scanf (使用標准輸入操作),使用sscanf ,它對字符串進行操作。
那就是

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

掃描第一個命令行參數。

看起來您想要將double值傳遞給您的程序。 但是您使用**argv來檢索從命令行傳遞的double。 **argv真的是一個單一的字符。

您需要做的是使用atof()將字符串轉換為double。

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

另一個潛在的問題是,這里: fabs(t - c/t)如果t變為0,你可能面臨歸零

要從終端運行命令行參數,您需要使用此語法

gcc filename.c

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM