[英]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.