这是确切的问题:
编写一个 C 程序,将一个字符作为输入并打印与该字符最接近的字母数字字符(0-9、A-Z、a-z 是字母数字字符)。注意:如果输入字符与两个字母数字值等距,则可以打印其中之一。
我知道我们必须使用 ASCII 表并制作一些案例,但我不知道如何准确地做到这一点。
最佳答案
是的,该解决方案依赖于 ASCII 值。您可以简单地使用 if-else-if 梯形图来找出与输入字符最接近的字母数字字符。如果输入已经是字母数字字符,则可以使用内置的 isalpha
和isdigit
功能快速得出解决方案。如果不是,则使用任一比较运算符 <
或>
,并找出您的解决方案位于这些范围 0-9、A-Z、a-z 的哪一端。
为了减少比较次数,进行比较的顺序很重要。这是ASCII Table供引用。
由于您是这个网站的新手,请使用我的代码并从中学习。但您可能并不总能在这里以完整代码的形式获得解决方案。
#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;
}
关于c - 如何在 C 程序中打印与输入字符最接近的字母数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015096/