【问题标题】:Conversion of base 10 to base 6将基数 10 转换为基数 6
【发布时间】:2019-11-27 00:21:25
【问题描述】:

我尝试在 C 中将一个以 10 为底的数字转换为以 6 为底的数字,但我的代码没有通过 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);

}

【问题讨论】:

  • 不检查溢出。
  • 这是一个 C 或 C++ 问题吗?测试的规范是什么?
  • 请展示挑战或家庭作业。有了一些经验(StackOverflow 用户会提供),通常你可以从那里阅读测试用例。
  • @ikegam 这是 C 题
  • @Viky 使用字符串/字符而不是 int 构建您的以 6 为基数的数字。基本循环有效,但数字的构建无效。

标签: c logic base base-conversion


【解决方案1】:

您的解决方案仅适用于有限范围的int

由于以 6 为底的数字将比以 10 为底的数字使用更多的数字,因此以 10 为底的数字将生成一个不适合 int 的以 6 为底的数字,从而产生溢出。

this example

一种解决方案是使用字符串生成以 6 为底的数字。该数字存储在字符数组中。

#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); 解决第一个问题。
  • 20 的来源不清楚,如 maxdigits = 20;。只是一些希望足够大的数字?
  • 我改为 26,因为这应该是 64 位数字的最大基数 6 位数。也改为do-while
【解决方案2】:

将数字转换为给定的基数应作为字符串完成。

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

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2011-06-25
    相关资源
    最近更新 更多