简体   繁体   English

C命令行输入

[英]Command Line Input in C

I made a program that inputs thru the command line 2 variables. 我制作了一个通过命令行2变量输入的程序。

If the input was 5 15 the output should be: 如果输入为5 15,则输出应为:

0.00 15.00 30.00 45.00 60.00
1.00 0.97 0.87 0.71 0.50

However in the command prompt whenever I type 5 15 I get: 但是,每当我键入5 15时,在命令提示符下我都会得到:

0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00

Here is my code: 这是我的代码:

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

The part that takes in the command line argument is this: 接受命令行参数的部分是这样的:

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

Here I am converting the argv values from strings to doubles, is this incorrect? 在这里,我将argv值从字符串转换为双精度,这不正确吗?

When trying to compile your code, I get the following warning: 尝试编译您的代码时,出现以下警告:

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

This implicit declaration points you towards the problem. implicit declaration您引向该问题。 You did not include stdlib.h Include it and your program will work. 您没有包括stdlib.h包括它,您的程序将运行。

Without the include the function atof() is declared implicitly. 如果没有include函数,则隐式声明atof()函数。 When GCC doesn't find a declaration (which is the case if you don't include the header needed), it assumes this implicit declaration: int atof() ;, which means the function can receive whatever you give it, and returns an integer. 当GCC找不到声明时(如果您不包括所需的标头,就是这种情况),它将假定此隐式声明:int atof()这意味着该函数可以接收您提供的任何内容,并返回一个整数。

This is considered an error (implicit declarations) in newer C standards (C99, C11). 在较新的C标准(C99,C11)中,这被视为错误(隐式声明)。 However, gcc doesn't implement these standards by default, so you still get the warning with older standards (that you're using I suppose). 但是,gcc默认情况下不会实现这些标准,因此您仍然会收到旧标准的警告(我想您正在使用)。

To better find these kind of errors I suggest your turn on and read the compiler warnings. 为了更好地发现此类错误,建议您打开并阅读编译器警告。 You should also give this link a read to learn about them. 您还应该阅读此链接以了解它们。

As pointed by @JonathanLeffler, you should also avoid the use of global variables :). 正如@JonathanLeffler指出的那样,您还应该避免使用全局变量:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM