c - 无法创建基于基本命令行参数的计算器

标签 c

我正在尝试创建一个简单的计算器,它从用户 [Number 1] [operator] [Number 2] 接收 3 个参数。运算符表示要完成的计算(+、-、x、/)。我决定为运算符(operator)使用开关盒。但是我似乎无法让我的代码工作。看起来很简单,但输出始终是默认的开关盒。

感谢您的帮助。

#include <stdio.h>

int main(int argc, char *argv[]) {
    int a,b,sol;
    char op;
    if ( argc != 4) {
         printf("Usage: calc [operand_1] [operator] [operand_2]\n");
         break;
    } 

    a = atoi(argv[1]);
    b = atoi(argv[3]);
    op = argv[2];

    switch (op)
    {
    case '+':
        sol=a+b;
        printf("%i\n",sol);
        break;
    case '-':
        sol=a-b;
        printf("%i\n",sol);
        break;        
    case 'x':
        sol=a*b;
        printf("%i\n",sol);
        break;       
    case '/':
        sol=a/b;
        printf("%i\n",sol);
        break;        
    default:
        printf("Invalid Operator \n");
    }

    return 0; 
}

最佳答案

argv[2] 是一个字符串,但在您的 switch 中您将其与一个字符进行比较。

改为这样做:

if(strcmp(op,"+") == 0)
   sol=a+b;

// etc
printf("%i\n",sol);

或者:

  op = *argv[2]; // get first char

  // rest of your code

关于c - 无法创建基于基本命令行参数的计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13662607/

相关文章:

c - OCaml - 编译使用 Ctypes 的 OCaml 和 C 代码

c++ - atol()、atof()、atoi() 函数行为,是否有稳定的方法从/到字符串/整数转换?

规范上下文中的 C 结构大小

c - 将任何数组类型传递给 C 中的函数

c - C 中声明 char * VS (char *)

c - gnuplot 通过 Shell 工作,C 接口(interface)什么都不做

c - C 中的线程如何工作?

c - (初级程序员)需要帮助 : Linked Lists in C

c - 程序循环次数过多,并产生奇怪的行为

c - 当在另一个文件中声明结构时,如何使用结构作为函数的参数?