【发布时间】:2021-12-10 20:54:04
【问题描述】:
我正在编写一个程序来计算 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]!='\0')
{
//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]!='\0')
{
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;
}
它有效,但我认为它有点复杂。所以想问问有没有办法优化检测。
以及如何处理大输入数。
任何帮助将不胜感激。
【问题讨论】:
-
请将您的minimal reproducible example 复制粘贴(作为文本!)到问题本身。问题需要是独立的,并且主要部分应该在内容可以随时更改或消失的网站上。
-
至于您的问题,the standard character classification functions 可能会有所帮助。
-
@Someprogrammerdude 谢谢,对我很有帮助
-
在发布您的下一个问题之前,请了解如何在问题中正确格式化您的代码(我已经为您完成了)。这很简单,只需几分钟即可学会。
-
我真的很感激。感谢您编辑我的帖子
标签: c optimization input