数组内多十进制值转十六进制代码异常,求修正方法
十进制转十六进制代码错误排查
我的目标是将数组中存储的十进制值转换为十六进制形式。目前代码仅能正确转换input[0](首次循环)和sum变量(最后一次循环),数组其余元素转换结果错误。以下是当前最接近正确的代码、实际输出及期望输出,请求协助排查修正:
#include <stdio.h> int main() { int dividend,base=3,i,remainder,counter; int sum=651,input[4]={512,128,9,5},x=4; char hex[1024]; if(base==3) { printf("\nThe number system is: Hexadecimal\n"); printf("The converted number is/are: "); for(i=0;i<=x;i++) { if(i==x) {dividend=sum;} else {dividend=input[i];} while(dividend!=0) { remainder=dividend%16; dividend/=16; if (remainder < 10) {hex[counter++] = 48 + remainder;} else {hex[counter++] = 55 + remainder;} } for(;counter>=0;counter--) { printf("%c",hex[counter]); } printf(","); counter=0; } } }
实际输出:
The number system is: Hexadecimal The converted number is/are: 200,280,89,85,28B,
期望输出:
The number system is: Hexadecimal The converted number is/are: 200,80,9,5,28B,
错误原因
- 打印索引错误:处理完一个数字后,
counter的值是转换后十六进制字符的总数,有效字符的索引范围是0到counter-1。原代码从counter开始打印,会输出hex[counter]这个未初始化的垃圾值,导致结果多了错误字符。 - 循环变量干扰:打印循环直接修改
counter的值,虽然最后重置为0,但逻辑混乱,容易引发索引越界问题。
修正后的代码
#include <stdio.h> int main() { int dividend, base=3, i, remainder, counter; int sum=651, input[4]={512,128,9,5}, x=4; char hex[1024]; if(base==3) { printf("\nThe number system is: Hexadecimal\n"); printf("The converted number is/are: "); for(i=0; i<=x; i++) { // 选择要转换的数字 dividend = (i == x) ? sum : input[i]; counter = 0; // 处理每个数字前重置计数器 if(dividend == 0) // 处理0的特殊情况 { hex[counter++] = '0'; } else { while(dividend != 0) { remainder = dividend % 16; dividend /= 16; hex[counter++] = (remainder < 10) ? (48 + remainder) : (55 + remainder); } } // 从最后一个有效字符倒序打印 for(int j = counter - 1; j >= 0; j--) { printf("%c", hex[j]); } printf(","); } } return 0; }
修正说明
- 处理每个数字前,先将
counter重置为0,确保每个转换都从数组起始位置开始。 - 打印时使用独立的
j变量,从counter-1(最后一个有效字符的索引)倒序遍历到0,避免打印垃圾值。 - 增加了对数字0的处理,避免出现死循环(提升代码健壮性)。
- 用三元运算符简化条件判断,代码更简洁。
内容的提问来源于stack exchange,提问作者haunt
相关产品推荐
相关产品推荐

