我做了一个程序,通过命令行2变量输入.
如果输入为5 15,则输出应为:
0.00 15.00 30.00 45.00 60.00
1.00 0.97 0.87 0.71 0.50
Run Code Online (Sandbox Code Playgroud)
但是在命令提示符中,每当我输入5 15时,我得到:
0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
接受命令行参数的部分是:
length = atof(argv[1]);
stepSize = atof(argv[2]);
Run Code Online (Sandbox Code Playgroud)
在这里,我将argv值从字符串转换为双精度,这是不正确的?
在尝试编译代码时,我收到以下警告:
test.c:15:11: warning: implicit declaration of function 'atof' is invalid in C99
[-Wimplicit-function-declaration]
length = atof(argv[1]);
Run Code Online (Sandbox Code Playgroud)
这implicit declaration指出了你的问题.您没有stdlib.h
包括它包含它,您的程序将工作.
如果没有include,atof()则隐式声明函数.当GCC没有找到声明时(如果你不包含所需的标题就是这种情况),它假设这个隐式声明:int;,atof()这意味着函数可以接收你给它的任何东西,并返回一个整数.
这被认为是较新的C标准(C99,C11)中的错误(隐式声明).但是,默认情况下,gcc没有实现这些标准,所以你仍然会收到旧标准的警告(我猜你正在使用它).
为了更好地发现这些错误,我建议你打开并阅读编译器警告.您还应该阅读此链接以了解它们.
正如@JonathanLeffler指出的那样,你也应该避免使用全局变量:).