代码之家  ›  专栏  ›  技术社区  ›  Glenn Claudio

运算选择中带有输入字符串的计算器[关闭]

  •  -3
  • Glenn Claudio  · 技术社区  · 7 年前

    如何在运算选择中使用输入字符串制作计算器?,我试过了,但没用。我的演讲分配:)

    printf("choose:");
    scanf("%s", (char *) &choose);
    
    switch(choose)
    {
    case 'tambah':
    printf("Masukkan Nilai 1:");
    scanf("%d", &x);
    printf("Masukkan Nilai 2:");
    scanf("%d", &y);
    hasil = tambah(x,y);
    printf("%d + %d = %d", x, y, hasil);
    break;
    
    case 'kurang':
    printf("Masukkan Nilai 1:");
    scanf("%d", &x);
    printf("Masukkan Nilai 2:");
    scanf("%d", &y);
    hasil = kurang(x,y);
    printf("%d - %d = %d", x, y, hasil);
    break;
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Gnqz    7 年前

    使用字符串(考虑到您使用字符串,因为在您的示例中,您只将几个字符放入文字中,文字应该是一个 char )直接输入 switch() C中的语句是一个糟糕的想法。我建议列举可能的选项,并在 strcmp 以便与您的运营和分支机构相匹配。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    enum {
    tambah = 0,
    kurang = 1
    };
    
    int decodeLineType(const char* strAction)
    {
      int i = 0;
    
      char acAllowedCodes[2][7] = {"tambah","kurang"};
    
      for(; i < 2; ++i)
      {
        if (strncmp(strAction, acAllowedCodes[i], strlen(acAllowedCodes[i])) == 0)
        {
          return i;
        }
      }
    
      return(-1);
    }
    
    int main()
    {
        char choose[30] = {0};
        scanf("%s", choose);
        switch(decodeLineType(choose))
        {
           case tambah :
             /* some logic here*/
           break;
           case kurang :
             /* some logic here*/
           break;
           default:
           break;
        }
        return(0);
    }
    

    主题外: 此外,当你准备在国际论坛上寻求指导时,请考虑在你的程序中使用英语作为所有标签和变量名。