【问题标题】:How to convert an integer to an array of its digits in C? [closed]如何将整数转换为C中的数字数组? [关闭]
【发布时间】:2014-11-24 07:21:38
【问题描述】:

如何将整数转换为 C 中的数字数组? 例如: 我有一个整数:int a=12345; 我想要一个包含其数字的数组:

int arrayofdigits={1,2,3,4,5};

【问题讨论】:

  • 你尝试过什么?
  • char buf[sizeof(int) * CHAR_BIT + 1]; snprintf(buf, sizeof buf, "%d", a);
  • @TheParamagneticCroissant 当然不需要 33 个字符来表示 32 位有符号整数,即使尾随空字符也是如此?
  • 签出this
  • @PascalCuoq 我不知道int 在 OP 的实现中是否为 32 位长。此缓冲区大小确保整数可以在 任何 可能的基数以及终止 NUL 中进行格式打印。安全总比后悔好。

标签: c arrays


【解决方案1】:

我们提供想法,您编写代码如何?听起来不错?

  1. 取整数。
  2. 使用取模[%]运算符取出最后一位。存储在数组中。
  3. 除以 10 可将原始数字右移 1 位。
  4. 迭代 2 和 3,直到 3 的结果变为 0。

最后,一旦你完成了,如果你已经直接存储了,你需要反转数组内容,以按照数字中出现的顺序获取数字。

【讨论】:

    【解决方案2】:

    您可以参考以下程序。
    我能想到的最简单的是:

    int main(void)
    {
        int a=12345;
        char c[10] = {0}; /*c is array if characters to hold the digits*/
    
        sprintf(c, "%d", a);
        printf("Int : %d, array of digits: %s\n", a, c);
    
        /*To print each digit one by one*/
        a = 0;
        while (c[a] != '\0')
            printf("%c\n",c[a++]);
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:
      1. 您可以使用x % 10 获取x 的单位(最右边)数字。这些数字中的每一个都可以放入一个数组中。

      2. 您可以使用x = x / 10x 除以十,从而有效地将所有数字右移。

      3. x 已移动到等于零的点时,您可以检测是否已用完数字。

      4. 你可以。如果您需要按正确的顺序使用它们,请从边缘移入直到您穿过中间来交换它们。

      所以这种野兽的伪代码是:

      def digits[10]
      def x = 12345
      
      def pos = 0
      while x != 0:
          digits[pos] = x % 10
          pos = pos + 1
          x = x / 10
      
      def left = 0
      def right = pos - 1
      while left < right:
          temp = digits[left]
          digits[left] = digits[right]
          digits[right] = temp
          left = left + 1
          right = right - 1
      
      # Now digits[0..(right-1)] holds the digits.
      

      【讨论】:

        猜你喜欢
        • 2018-05-18
        • 1970-01-01
        • 1970-01-01
        • 2015-01-06
        • 1970-01-01
        • 2013-07-18
        • 1970-01-01
        • 1970-01-01
        • 2011-08-13
        相关资源
        最近更新 更多