您的代码的此编辑显示了如何使用您输入的两个数字来使用您的函数 2。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun_one(int a,int b);
void fun_two(int a,int b);
int main(int, char **);
int main(int argc, char ** argv)
{
int a,b;
a= atoi(argv[1]);
b=atoi(argv[2]);
printf("Result=");fun_two(a,b); // similar to what you want from comments
//using both functions
printf("a+b=");fun_one(a,b);
printf("a*b=");fun_two(a,b);
return 0;
}
void fun_one(int a,int b){
printf("%d\n",a+b);
return;
}
void fun_two(int a,int b){
printf("%d\n",a*b);
return;
}
我已经修改了你的代码,所以如果你编译它
gcc -o exec exec.c
您将能够运行它
./exec 4 3
要获得所需的输出 - 请注意,我希望使用 cc 进行编译将给出完全相同的输出,但我无法对其进行测试。
我所做的是更改了main 的定义,以便它可以在您调用它时接受输入。额外的位被放入字符串中。
函数atoi将ascii字符串转换为一个整数数字,这样你在命令行中输入的数字就可以被处理为数字而不是字符串。
请注意,此代码相当脆弱,可能会出现分段。过错。如果你在调用程序后没有输入两个数字,结果将是不可预测的。您可以通过检查 argc 的值来使其更可靠 - 输入命令时在行上键入的内容的数量并检查 atoi 是否有效,但这会使代码更长,我认为更重要的是看到做你现在想要达到的目标的方式。
下面是一个更通用的代码,它允许您选择要在代码中运行的函数....
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun_one(int a,int b);
void fun_two(int a,int b);
int main(int, char **);
int main(int argc, char ** argv)
{
int a,b;
a= atoi(argv[2]);
b=atoi(argv[3]);
if (!strcmp("fun_one",argv[1]))
{
printf("Result=");fun_one(a,b);
}
else if (!strcmp("fun_two",argv[1]))
{
printf("Result=");fun_two(a,b);
}
else printf("Didn't understand function you requested. \n\n");
return 0;
}
void fun_one(int a,int b){
printf("%d\n",a+b);
return;
}
void fun_two(int a,int b){
printf("%d\n",a*b);
return;
}
该函数现在为以下输入提供以下输出
./exec fun_three 3 4
Didn't understand function you requested.
./exec fun_one 3 4
Result=7
./exec fun_two 3 4
Result=12
所以现在使用上面的代码,您在命令后输入三件事 - 您想要的功能,然后是两个数字 - 如果无法识别该功能,则会出现错误消息。
函数strcmp 比较两个字符串,如果它们相同则返回零。零在逻辑上等于假,因此! 符号用作非,它将零转换为一,将不等于零的数字转换为零。效果是如果两个字符串相同,则逻辑测试为真。