C语言奇偶判断程序优化:支持0-9999数字并处理非法输入
解决方案
要扩展数字判断范围到0-9999,核心是把输入从单个字符改为字符串处理,这样既能容纳多位数,也能保留对单个字母、特殊符号的识别逻辑。以下是修改后的代码:
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> // 判断字符串是否为纯数字 int is_all_digits(const char *str) { while (*str) { if (!isdigit(*str)) { return 0; } str++; } return 1; } int main() { char input[20]; // 足够容纳0-9999及其他输入 printf("Enter anything here: "); scanf("%s", input); // 读取字符串输入 int len = strlen(input); // 先判断是否为纯数字 if (is_all_digits(input)) { int num = atoi(input); // 检查是否在0-9999范围内 if (num >= 0 && num <= 9999) { if (num % 2 == 0) { printf("%d is an Even Number.\n", num); } else { printf("%d is an Odd Number.\n", num); } } else { printf("Number out of range (0-9999).\n"); } } else { // 非纯数字的情况,判断是否为单个字母 if (len == 1) { char c = input[0]; if (isupper(c)) { printf("%c is an Uppercase Alphabet.\n", c); } else if (islower(c)) { printf("%c is a Lowercase Alphabet.\n", c); } else { printf("Special Symbol.\n"); } } else { // 多字符且非纯数字,归为特殊符号类 printf("Special Symbol.\n"); } } return 0; }
关键修改说明:
- 输入处理:改用
char input[20]存储输入,支持多字符内容,替换原有的单个char变量。 - 纯数字判断:新增
is_all_digits函数,遍历字符串确认每个字符都是数字。 - 数字范围与奇偶判断:用
atoi将纯数字字符串转为整数,先检查是否在0-9999区间内,再判断奇偶性。 - 非数字逻辑保留:对于非纯数字的输入,若为单个字符则判断大小写字母,否则直接判定为特殊符号。
- 使用标准库函数:用
isdigit、isupper、islower替代硬编码的ASCII值,代码可读性更强且跨平台兼容。
内容的提问来源于stack exchange,提问作者Deanjmss
相关产品推荐
相关产品推荐

