簡體   English   中英

C命令行輸入

[英]Command Line Input in C

我制作了一個通過命令行2變量輸入的程序。

如果輸入為5 15,則輸出應為:

0.00 15.00 30.00 45.00 60.00
1.00 0.97 0.87 0.71 0.50

但是,每當我鍵入5 15時,在命令提示符下我都會得到:

0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00

這是我的代碼:

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

#define PI 3.14159265

char buff[256];
double length;
double stepSize;
double cosValue;
double val = PI / 180.0;
double i;

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

    length = atof(argv[1]);
    stepSize = atof(argv[2]);

    for (i = 0; i < length; i++) {
        double stepSizeEdit = stepSize * i;
        printf("%.2lf ", stepSizeEdit);
    }

    printf("\n");

    for (i = 0; i < length; i++) {
        double stepSizeEdit = stepSize * i;
        cosValue = cos(stepSizeEdit * val);
        printf("%.2lf ", cosValue);
    }
}

接受命令行參數的部分是這樣的:

length = atof(argv[1]);
stepSize = atof(argv[2]);

在這里,我將argv值從字符串轉換為雙精度,這不正確嗎?

嘗試編譯您的代碼時,出現以下警告:

test.c:15:11: warning: implicit declaration of function 'atof' is invalid in C99
      [-Wimplicit-function-declaration]
        length = atof(argv[1]);

implicit declaration您引向該問題。 您沒有包括stdlib.h包括它,您的程序將運行。

如果沒有include函數,則隱式聲明atof()函數。 當GCC找不到聲明時(如果您不包括所需的標頭,就是這種情況),它將假定此隱式聲明:int atof()這意味着該函數可以接收您提供的任何內容,並返回一個整數。

在較新的C標准(C99,C11)中,這被視為錯誤(隱式聲明)。 但是,gcc默認情況下不會實現這些標准,因此您仍然會收到舊標准的警告(我想您正在使用)。

為了更好地發現此類錯誤,建議您打開並閱讀編譯器警告。 您還應該閱讀此鏈接以了解它們。

正如@JonathanLeffler指出的那樣,您還應該避免使用全局變量:)。

暫無
暫無

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

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