代码之家  ›  专栏  ›  技术社区  ›  user3444477

带有二进制运算符的c编程错误

  •  0
  • user3444477  · 技术社区  · 10 年前

    我想写一个计算器程序。我已经写了它的第一部分,但我一直都是这样 错误:类型的操作数无效 unsigned int*' and char[80]”转换为二进制“operator&” 请帮帮我

     #include <stdio.h>
     #include <string.h>
     #include <math.h>
     #include <stdlib.h>
     unsigned int num1, num2, num3;
     char s[80];
     int main (){
      printf("type in an expression:   ");
      scanf(" %x %s %x\n", &num1 &s &num2);
      if(strcmp ("add", s) == 0){
        num3 = num1 + num2;
     }
     if(strcmp("subtract", s) == 0){
        num3 = num2 - num1;
     }
     printf("the answer is: %x", num3);
    }   
    
    2 回复  |  直到 10 年前
        1
  •  0
  •   Yohanes Khosiawan 许先汉    10 年前

    尝试:

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    unsigned int num1, num2, num3;
    char s[80];
    int main (){
        printf("type in an expression:   ");
        scanf(" %x %s %x", &num1, s, &num2);
        if(strcmp ("add", s) == 0){
            num3 = num1 + num2;
        }
        if(strcmp("subtract", s) == 0){
            num3 = num2 - num1;
        }
        printf("the answer is: %x\n", num3);
        system("pause");
    }
    

    注意:请注意,我删除了 \n scanf ..

        2
  •  0
  •   James Card    10 年前

    正如Yohanes所提到的,您需要在scanf中的参数之间使用逗号,否则编译器会尝试这样做:获取num1(&num1)的地址,并将其与数组s的地址进行逻辑“与”运算(此处隐含了地址,因为它是一个数组),然后将其与num2中包含的值进行逻辑“和”运算。

    我建议您在两个if语句之间添加一个else,因为它们是互斥的。

    此外,您可能希望在printf语句中添加\n

    printf("the answer is: %x\n", num3);
    

    以刷新输出。