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

标签 c printf character ascii alphanumeric

这是确切的问题:

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

我知道我们必须使用 ASCII 表并制作一些案例,但我不知道如何准确地做到这一点。

最佳答案

是的,该解决方案依赖于 ASCII 值。您可以简单地使用 if-else-if 梯形图来找出与输入字符最接近的字母数字字符。如果输入已经是字母数字字符,则可以使用内置的 isalphaisdigit功能快速得出解决方案。如果不是,则使用任一比较运算符 <> ,并找出您的解决方案位于这些范围 0-9A-Za-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/

相关文章:

c++ - 现在的 C 和 C++ 编译器的线程保证是什么?

multidimensional-array - F# 打印出一个二维字符串数组

c++ - sfml 2.0 中的速度和耗时

jquery - 类似 Twitter 的文本框字符计数,带有内联警报

c++ - 如何将带有转义字符的 C/C++ 字符串转换为普通(原始)字符串

c - 将文件描述符的整数值写入文件

c - 使用 bluez 从 C 中的 ble 设备访问电池服务的示例代码

C switch case 值不能在 switch 内修改(不是常量)

c - 将 C 字符串转换为 double 或从 double 转换时的奇怪行为

c - 正确sscanf使用麻烦