将字符转换为整数并将它们添加到 C 中

标签 c pointers

我正在尝试根据用户字符输入添加数字。如果用户输入 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

最佳答案

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

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

关于将字符转换为整数并将它们添加到 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18677579/

相关文章:

c - 结构指针释放导致错误

c - 共享内存 - 警告 : Comparison Between Pointer and Integer

c++ - 在 C++ 的析构函数中删除指针后,将 NULL 分配给指针是否有任何用处?

c - Yacc, union 结构指针

c - 使用 DOSBox 版本 0.74 在 C 中出现多重声明错误

c - 计算一个值在数组中出现次数的最佳方法是什么?

c++ - C++:通过函数传递指针数组的语法

c - 函数返回从 main() 调用两次的指针

c - 作为函数类型的结构

C 中字符与字符串的比较