我试图根据用户的char输入添加数字。如果用户输入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
答案 0 :(得分:2)
根本不需要切换或比较。对于char
中的单个数字输入,只需减去'0'
并将结果转换为int
。
为了获得稳健性,您可能需要先进行范围检查,即验证该字符是&gt; ='0'和&lt; ='9'。
答案 1 :(得分:1)
你将单个字符('2'等)与字符串指针(“2”等)进行比较。非常不同的东西
尝试:
if (a == '2') {
x = 2;
}
等等。