【问题标题】:How to put an integer to an array of digits [closed]如何将整数放入数字数组[关闭]
【发布时间】:2013-09-09 13:33:00
【问题描述】:

我想将一个像 123456 这样的数字放入一个数字数组中。你能给我一个过程的提示吗?我可以定义一个元素个数未知的数组吗?

【问题讨论】:

  • 所需的位数可以通过使用以 10 为底的对数(并加 1)求出。之后,只需要修改 10 再除以 10 即可。
  • 什么语言编程? C 还是 C++?
  • @MohsenPahlevanzadeh:它被标记为 C。
  • 提示:123456 % 10123456 / 10 得到什么?
  • myvar = 1233456 % 10 ; // mod 运算符 and : myvar = 123345 / 10 ; //划分运算符

标签: c


【解决方案1】:

先计算位数

int count = 0;
int n = number;

while (n != 0)
{
    n /= 10;
    cout++;
}

现在初始化数组并分配大小:

if(count!=0){
   int numberArray[count];

   count = 0;    
   n = number;

   while (n != 0){
       numberArray[count] = n % 10;
       n /= 10;
       count++;
   }
}

【讨论】:

  • 小心number == 0,因为那样会创建一个大小为零的数组(这是未定义的行为)。
  • 忘记添加那个条件,一定会编辑那个。谢谢指出
  • 谢谢。这非常有帮助!我是新手
  • 如果对您有帮助,请接受答案:了解接受答案的工作原理:meta.stackexchange.com/questions/5234/…
【解决方案2】:

如果你不介意使用char作为数组元素类型,可以使用snprintf()

char digits[32];
snprintf(digits, sizeof(digits), "%d", number);

每个数字都将表示为字符值'0''9'。要获得整数值,请将字符值减去'0'

int digit_value = digits[x] - '0';

【讨论】:

    【解决方案3】:

    “我可以定义一个元素个数未知的数组吗?”

    如果数字太大,您可以将其输入为字符串,然后从中提取相应的数字

    类似以下内容:

    char buf[128];
    int *array;
    //fscanf(stdin,"%s",buf);
    
    array = malloc(strlen(buf) * sizeof(int)); //Allocate Memory
    int i=0;
    do{
     array[i] = buf[i]-'0'; //get the number from ASCII subtract 48
     }while(buf[++i]); // Loop till last but one 
    

    【讨论】:

      【解决方案4】:
      int x[6];
      int n=123456;
      int i=0;
      while(n>0){
         x[i]=n%10;
         n=n/10;
         i++;
      }
      

      【讨论】:

      • 当我计算 123456 中的数字时,它们似乎不适合包含五个项目的数组。
      • 你需要 x[6] 因为有 6 位数字!
      【解决方案5】:

      这里是步骤。首先,获取存储数字中所有数字所需的大小——对数组进行 m​​alloc。接下来,取数字的模,然后将数字除以 10。继续这样做,直到用完数字中的所有数字。

      【讨论】:

        猜你喜欢
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        • 2013-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        相关资源
        最近更新 更多