【发布时间】:2015-06-02 15:04:56
【问题描述】:
我编写了一个代码来执行从命令行获取输入的简单算术运算。所以如果我想做一个乘法,我会在终端中输入“prog_name 2 * 3”,它应该输出“Product:6”。
问题是,除了乘法之外,所有操作都有效。经过一番测试,我发现第三个参数(argc[2])是用来获取操作符的,实际上是存储程序名。那么我怎样才能使这项工作呢?
这是代码:
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
int a, b;
if(argc != 4)
{
printf("Invalid arguments!");
system("pause");
exit(0);
}
a = atoi(argv[1]);
b = atoi(argv[3]);
switch(*argv[2])
{
case '+':
printf("\n Sum : %d", a+b);
break;
case '-':
printf("\n Difference : %d", a-b);
break;
case '*':
printf("\n Product : %d", a*b);
break;
case '/':
printf("\n Quotient : %d", a/b);
break;
case '%':
printf("\n Remainder: %d", a%b);
break;
default:
printf("\n Invalid operator!");
}
}
【问题讨论】:
-
这个问题已经在两天前被问过了,而且有很多骗子!
-
你不使用 x 进行乘法吗?这只是性格问题:-)
-
@ Yasir 我曾想过,但我只是想知道为什么 * 不起作用。我实际上在发布之前搜索了很多,但没有找到任何相关内容。
标签: c command-line