C语言多十六进制值循环转换为十进制的实现问题咨询
实现多输入转换的修改方案如下
你可以将单次转换逻辑封装为独立函数,在外层套3次循环实现需求,同时修复原代码存在的小问题,修改后完整代码:
#include <stdio.h> #include <string.h> #define ARRAY_SIZE 20 // 独立封装十六进制转十进制逻辑 long long hex_to_dec(char *hex) { long long decimal = 0, base = 1; int length = strlen(hex); for(int i = length - 1; i >= 0; i--) { if(hex[i] >= '0' && hex[i] <= '9') { decimal += (hex[i] - 48) * base; base *= 16; } else if(hex[i] >= 'A' && hex[i] <= 'F') { decimal += (hex[i] - 55) * base; base *= 16; } else if(hex[i] >= 'a' && hex[i] <= 'f') { decimal += (hex[i] - 87) * base; base *= 16; } } return decimal; } int main() { char hex[ARRAY_SIZE]; long long dec_results[3]; // 存储3个转换结果,后续计算直接取用 for(int cnt = 0; cnt < 3; cnt++) { printf("请输入第%d个十六进制数: ", cnt+1); fgets(hex, ARRAY_SIZE, stdin); // 处理fgets读取到的换行符 int len = strlen(hex); if(len > 0 && hex[len-1] == '\n') { hex[len-1] = '\0'; } dec_results[cnt] = hex_to_dec(hex); printf("Hexadecimal number = %s\n", hex); printf("Decimal number = %lld\n\n", dec_results[cnt]); } // 后续其他计算逻辑可直接使用dec_results[0]、dec_results[1]、dec_results[2] return 0; }
核心改动说明
- 转换逻辑抽为独立函数,避免重复编码,也避免多次转换时变量残留上次的计算值
- 外层新增3次循环逻辑,转换结果存入数组,后续不同计算场景直接取下标对应的值即可
- 移除C标准中未定义行为的
fflush(stdin),改为主动处理fgets读取的换行符,避免转换结果出错 - 修正原代码遍历起始下标的逻辑问题,避免无效空字符干扰计算
内容的提问来源于stack exchange,提问作者Vale
相关产品推荐
相关产品推荐

