如何在 C 程序中打印最接近字符输入的字母数字?



这是确切的问题:

编写一个 C 程序,该程序将字符作为输入并打印最接近此字符的字母数字字符(0-9、A-Z、a-z 是字母数字字符(。注意:如果输入字符与两个字母数字值等距,则可以打印任何一个。

我知道我们必须使用 ASCII 表并制作一些案例,但我无法弄清楚如何做到这一点。

是的,该解决方案依赖于 ASCII 值。您可以简单地使用if-else-if 梯子来找出最接近输入字符的字母数字字符。如果输入已经是字母数字字符,则可以使用内置的isalphaisdigit函数快速得出解决方案。如果不是,则使用比较运算符中的任何一个<>,并找出您的解决方案位于这些范围0-9A-Za-z的哪一端。

为了减少比较次数,进行比较的顺序很重要。这是供参考的 ASCII 表。

由于您是这个网站的新手,请接受我的代码并从中学习。但是,您可能不会总是在这里以完整代码的形式获得解决方案。

#include <stdio.h>
#include <ctype.h>
int main()
{
unsigned char input, tmp, result;
printf("Enter the input character: ");
scanf("%c", &input);
if (isalpha(input))
{
tmp = input - 1;
result = isalpha(tmp) ? tmp : input + 1;
}
else if (isdigit(input))
{
tmp = input - 1;
result = isdigit(tmp) ? tmp : input + 1;
}
else if (input < '0')
{
result = '0';
}
else if (input > '9' && input < 'A')
{
result = (input - '9' > 'A' - input) ? 'A' : '9';
}
else if (input > 'Z' && input < 'a')
{
result = (input - 'Z' > 'a' - input) ? 'a' : 'Z';
}
else
{
result = 'z';
}
printf("Alphanumeric character closest to '%c' is '%c'", input, result);
return 0;
}

最新更新