从十进制转换为六进制

3

我尝试在C语言中将十进制数转换为六进制数,但我的代码没有通过2个隐藏测试用例。

我找不到任何逻辑错误。

你能帮忙看看吗?

//convert base 10 to base 6

#include<stdio.h>
int main()
{
   int num, rem = 0, i = 1, res = 0;
   scanf("%d", &num);
   while(num!=0)
   {
       rem = num%6;
       res = (rem*i)+res;
       num = num/6;
       i = i*10;
   }
   printf("%d",res);

}

2
不检查溢出。 - PaulMcKenzie
2
这是一个C还是C++的问题?这是根据哪个规范进行测试的? - ikegami
请展示挑战或作业任务。通常情况下,有经验的用户(StackOverflow用户将提供)可以从那里阅读测试用例。 - Yunnosch
@ikegam 这是一个关于 C 语言的问题。 - Viky
4
使用字符串/字符而不是int来构建你的六位数。基本循环可以正常工作,但是构建数字的部分有问题。 - PaulMcKenzie
显示剩余8条评论
2个回答

4

你的解决方案只适用于有限范围的 int

由于六进制比十进制使用更多的数字,因此会出现一种情况,即十进制数将生成一个无法适应 int 的六进制数,从而产生溢出。

请参见此示例

一个解决方案是使用字符串生成六进制数。该数字存储在字符数组中。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
   const int maxdigits = 26;    /* max number of base 6 digits for a 64 bit int */
   int num=123456789, rem = 0;

   /* handle negative input */
   int tempnum = abs(num);

   int lastpos = maxdigits-1;

   /* initialize array, and initialize array to spaces */
   char res[maxdigits + 1];
   memset(res, ' ', maxdigits);

   /* null terminate */
   res[maxdigits] = 0;

   do 
   {
       rem = tempnum % 6;
       res[lastpos--] = rem + '0'; /* set this element to the character digit */
       tempnum /= 6;
   } while (tempnum > 0);
   printf("%s%s", (num < 0)?"-":"", res + lastpos + 1); /* print starting from the last digit added */
}

输出:

20130035113

代码在num==0(没有数字)或者num==INT_MIN(UB)时会出现问题。建议使用do { ...} while(tempnum != 0);来解决第一个问题。 - chux - Reinstate Monica
20的来源不明确,例如maxdigits = 20;。只是希望使用足够大的数字? - chux - Reinstate Monica
1
我将数字更改为26,因为这应该是64位数字的最大六进制位数。同时,我也将代码更改为“do-while”循环。 - PaulMcKenzie

2

把一个数字转换成给定的进制应该以字符串形式进行。

这里有一个简单通用的转换函数:

Original Answer: Converting a number to a given base should be done as a string.

最初的回答:将数字转换为指定进制应以字符串形式进行。

这是一个简单通用的转换函数:

#include <stdio.h>

char *convert(char *dest, size_t size, int val, int base) {
    static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    char buf[66];
    char *p = buf + sizeof(buf);
    unsigned int n = val;

    if (base < 2 || base > 36 || !dest || size == 0)
        return NULL;
    if (val < 0)
        val = -n;

    *--p = '\0';
    while (n >= base) {
        *--p = digits[n % base];
        n /= base;
    }
    *--p = digits[n];
    if (val < 0)
        *--p = '-';
    if (buf + sizeof(buf) - p > size) {
        buf[size - 1] = '\0';
        return memset(buf, size - 1, '*');
    } else {
        return memcpy(dest, p, buf + sizeof(buf) - p);
    }
}

int main() {
    char buf[32];
    int num;

    while (scanf("%d", &num)) {
        printf("%d -> %s\n", num, convert(buf, sizeof buf, num, 6);
    }
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接