c - 检测输入是字符还是数字
问题描述
我正在编写一个程序来计算 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;
}
它有效,但我认为它有点复杂。所以想问问有没有办法优化检测。
以及如何处理大输入数。
任何帮助,将不胜感激。
解决方案
您可以使用stroll
函数将字符串转换为long long
. 它看起来更干净,并且该程序可以将 from 处理-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;
}
推荐阅读
- javascript - 循环到新的
- java - 我什么时候应该将对象包私有或公开?
- imacros - 如何在excel中获取每一列和每一行的数据并使用i宏放置另一个表格
- android - 尽管安装在实际设备上,但 APK 未能在 AVD 上安装
- ruby-on-rails - 验证正则表达式的基本电话号码
- javascript - 抛出某些 Redux 操作时,将 javascript 功能放在哪里?
- azure-active-directory - 希望为 myapps.Microsoft.com 配置自定义 URL
- python - 不和谐机器人问题
- asp.net-core - 运行时是否需要 .NET Core SDK?
- node.js - pubsub 如何知道我在某个时间点发布了多少条消息?