0

我试图根据用户字符输入添加数字。如果用户输入 2,我想为我的变量 x 分配数字 2;然后,如果用户输入 4,我希望我的变量 y 为数字 4。如果他们输入 t,我想为 z 分配数字 10。然后添加 2 + 4 + 10 并输出答案 = 16。有什么建议吗?谢谢!

#include<stdio.h> 
int main(){
char a,b,c;
int numbers;
int answer;
int x,y,z;
printf("How many numbers would you like to add? (2-3): ");
scanf(" %d", &numbers);

printf("\nEnter value of your numbers. (2-9), T (for 10)\n");
scanf(" %c %c %c", &a, &b, &c);


if(numbers == 3){
    if(a == "2"){
    x = 2;
    }
    if(a == "3"){
    x = 3;
    }
    if(a == "4"){
    x = 4;
    }
    if(a == "5"){
    x = 5;
    }
    if(a == "6"){
    x = 6;
    }
    if(a == "7"){
    x = 7;
    }
    if(a == "8"){
    x = 8;
    }
    if(a == "9"){
    x = 9;
    }
    if(a == "T" || a =="t"){
    x = 10;
    }

        if(b == "2"){
        y = 2;
        }
        if(b == "3"){
        y = 3;
        }
        if(b == "4"){
        y = 4;
        }
        if(b == "5"){
        y = 5;
        }
        if(b == "6"){
        y = 6;
        }
        if(b == "7"){
        y = 7;
        }
        if(b == "8"){
        y =8;
        }
        if(b == "9"){
        y = 9;
        }
        if(b == "T" || b =="t"){
        y = 10;
        }

            if(c == "2"){
            z = 2;
            }
            if(c == "3"){
            z = 3;
            }
            if(c == "4"){
            z = 4;
            }
            if(c == "5"){
            z = 5;
            }
            if(c == "6"){
            z = 6;
            }
            if(c == "7"){
            z = 7;
            }
            if(c == "8"){
            z = 8;
            }
            if(c == "9"){
            z = 9;
            }
            if(c == "T" || c =="t"){
            z = 10;
            }
    printf("\nA = %c B = %c C = %c", a, b, c);
    printf("\nx = %d y = %d z = %d", x, y, z);
    answer = x + y + z;
    printf("\nAnswer = %d\n",  answer); 
}


return 0;
}

我的输出是:

How many numbers would you like to add? (2-3): 3

Enter value of your numbers. (2-9), T (for 10)
2 4 T

A = 2 B = 4 C = T
x = 0 y = 4195472 z = 0
Answer = 4195472

我也收到此警告:

warning: comparison between pointer and integer
4

2 回答 2

2

根本不需要切换或比较。对于 a 中的单个数字输入char,只需将结果相减'0'并转换为 a int

为了稳健性,您可能需要先进行范围检查,即验证字符是否 >= '0' 和 <= '9'。

于 2013-09-07T20:31:57.133 回答
1

您正在将单个字符(“2”等)与字符串指针(“2”等)进行比较。非常不同的东西

尝试:

if (a == '2') {
  x = 2;
}

等等。

于 2013-09-07T20:27:50.227 回答