You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组内多十进制值转十六进制代码异常,求修正方法

十进制转十六进制代码错误排查

我的目标是将数组中存储的十进制值转换为十六进制形式。目前代码仅能正确转换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,

错误原因

  1. 打印索引错误:处理完一个数字后,counter的值是转换后十六进制字符的总数,有效字符的索引范围是0到counter-1。原代码从counter开始打印,会输出hex[counter]这个未初始化的垃圾值,导致结果多了错误字符。
  2. 循环变量干扰:打印循环直接修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:50:24