检测输入是字符还是数字
Detect input is character or number
我正在编写一个程序来计算 2 个变量的总和。其中一个是从 1 到 10 的数字,另一个是字母表中的一个字母(大写),其值与其顺序相对应。输入只能是数字、字母或两者。
例如:
输入
10 7
C 8
E D
9 F
输出
17
11
9
15
这是我的代码(这个问题应该发布在 codereview 上,但由于某些原因我无法在 codereview 上正确格式化代码。请原谅我)。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
char a[3], b[3];
int m,n;
//these variables hold the value of grade after converted
scanf("%s%s", a, b);
if (a[1]!='[=12=]')
{
//this is because only number 10 has 2 digits
m=10;
}
else if (a[0]>=49 && a[0]<=57)
{
m=a[0]-48; //in ascii table, 49 stands of 1 and 57 stands for 9
}
else
{
m=a[0]-64; //in ascii table, 65 stands for 'A'
}
if (b[1]!='[=12=]')
{
n=10;
}
else if (b[0]>=49 && b[0]<=57)
{
n=b[0]-48;
}
else
{
n=b[0]-64;
}
printf("%d", m+n);
return 0;
}
它可以工作,但我认为它有点复杂。所以想问问有没有办法优化检测
以及如何处理大输入数字。
如有任何帮助,我们将不胜感激。
您可以使用 stroll
函数将字符串转换为 long long
。它看起来干净多了,这个程序可以处理从 -9223372036854775808
到 9223372036854775807
作为输出。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char string_num1[20], string_num2[20];
scanf("%s%s", string_num1, string_num2);
long long num1 = strtoll(string_num1, NULL, 10);
long long num2 = strtoll(string_num2, NULL, 10);
long long num3 = num1 + num2;
printf("%lld", num3);
return 0;
}
我正在编写一个程序来计算 2 个变量的总和。其中一个是从 1 到 10 的数字,另一个是字母表中的一个字母(大写),其值与其顺序相对应。输入只能是数字、字母或两者。
例如:
输入
10 7
C 8
E D
9 F
输出
17
11
9
15
这是我的代码(这个问题应该发布在 codereview 上,但由于某些原因我无法在 codereview 上正确格式化代码。请原谅我)。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
char a[3], b[3];
int m,n;
//these variables hold the value of grade after converted
scanf("%s%s", a, b);
if (a[1]!='[=12=]')
{
//this is because only number 10 has 2 digits
m=10;
}
else if (a[0]>=49 && a[0]<=57)
{
m=a[0]-48; //in ascii table, 49 stands of 1 and 57 stands for 9
}
else
{
m=a[0]-64; //in ascii table, 65 stands for 'A'
}
if (b[1]!='[=12=]')
{
n=10;
}
else if (b[0]>=49 && b[0]<=57)
{
n=b[0]-48;
}
else
{
n=b[0]-64;
}
printf("%d", m+n);
return 0;
}
它可以工作,但我认为它有点复杂。所以想问问有没有办法优化检测
以及如何处理大输入数字。
如有任何帮助,我们将不胜感激。
您可以使用 stroll
函数将字符串转换为 long long
。它看起来干净多了,这个程序可以处理从 -9223372036854775808
到 9223372036854775807
作为输出。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char string_num1[20], string_num2[20];
scanf("%s%s", string_num1, string_num2);
long long num1 = strtoll(string_num1, NULL, 10);
long long num2 = strtoll(string_num2, NULL, 10);
long long num3 = num1 + num2;
printf("%lld", num3);
return 0;
}