【问题标题】:decimal to binary, oct and hex number failing in C十进制到二进制,八进制和十六进制数在C中失败
【发布时间】:2021-06-08 20:55:54
【问题描述】:

按照简单的十进制到二进制、八进制或十六进制转换失败。以下是问题陈述,

编写一个名为 itoc() 的函数,它将无符号整数转换为二进制、八进制或十六进制字符串。将转换基作为参数传递给 itoc() 并让它返回一个以 NULL 结尾的字符串。

我以相反顺序转换输入数字的第一部分。这些中间结果是正确的(或者我认为它是正确的)。最后的逆转没有任何回报。 2 个字符数组 str[] 和 outPutString[] 上的监视窗口显示以下内容...认为我的代码中有错误,但我无法弄清楚缺少什么。

//itoc.c
    
#include <stdio.h>
#include <string.h>

char *itoc(unsigned int, unsigned int);

int main(void)
{
   // variable to store base and decimal number for conversion
   unsigned int base, number;

   printf("Enter <number> and <base> here: ");
   scanf("%u %u", &number, &base);
   printf("%u is %s\n", number, itoc(base, number));

   return 0;
}

// function converts any decimal number and convert based upon base
char *itoc(unsigned int base, unsigned int number)
{
   static char str[80], outPutStr[80];       //string to hold the intermediate
                                             // results and final result
   char *ptrChar, *ptrEnd;                   // current location and final location
   unsigned int digit;

   //divide a number by base and append the remainder to an intermediate array continue to divide the 
   //number until remainder is zero. in case of hex, number greater than 9 are added with offset
   for(ptrChar = str; number > 0;)
   {
      digit = number % base;
      
      if(digit <= 9)
         *ptrChar++ = digit + '0';
      else
         *ptrChar++ = digit + 'A' - 10;

      number /= base;
   }
   *ptrChar = '\0';                       // terminate the array

   ptrChar = outPutStr;
   ptrEnd = str + (int)strlen(str);       // point to the last location of
                                          // intermediate array

   // un-reverse the internediate array holds converted number in reverse order
   for(; ptrEnd >= str;)
   {
      *ptrChar++ = *ptrEnd--;
   }
   *ptrChar = '\0';

   return outPutStr;                      // return pointer to final result
}

【问题讨论】:

  • 提示:for ( ; cond ;) 是一种笨拙的说法 while (cond)
  • 当您首先复制 '\0' 终止字符开始时,可​​能会出现一个错误。

标签: c


【解决方案1】:

问题来了:

ptrEnd = str + (int)strlen(str);       

结束指针开始指向字符串末尾的空终止字节。所以你用第一个字符交换它,现在你的字符串以一个空字节开始,给你一个空字符串。

将其更改为指向字符串中的最后一个字符:

ptrEnd = str + (int)strlen(str) - 1;       

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2015-12-12
    • 2014-03-11
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多