【问题标题】:C Program To Count Each Digit In A Number using 2 ArraysC程序使用2个数组计算数字中的每个数字
【发布时间】:2021-03-21 17:25:31
【问题描述】:

我需要编写一个名为void digits (int arr [], int size, int statistics []) 的函数,该函数接收一个整数数组及其大小,以及另一个大小为 10 的称为统计数据的数组。 该函数更改数组统计信息,使其包含 数组数组中的每个告诉的印象数。即统计[i]包含数量 故事的出现 i.该函数不会更改“arr”数组,也不会打印任何内容。 例如,如果arr [] = {438,439,440,441,442,443,444} 那么在函数运行结束时 statistics [] = {1,1,1,3,13,0,0,0,1,1}。即数字0在“arr”数组中出现一次,数字1 在“arr”数组等中出现一次。

【问题讨论】:

  • 请贴出您为作业尝试过的代码

标签: arrays c counter


【解决方案1】:

您应该使用 mod 和除法来过滤掉数字。 然后使用该数字作为统计数组中的索引并递增相关元素。

类似这样的:

void digits(int arr [], int size, int statistics []) {
  for(int i=0 ; i<10 ; i++) {  
    statistics[i] = 0
  }
  for (int i=0 ; i< size ; i++) {
     int remainder = arr[i];
     do{
        int digit = remainder % 10;
        remainder = remainder / 10;
        statistics[i]++;
     }while(remainder) ;
  }
}

为您的代码编写测试用例也是一个好习惯,对于像这样的快速破解,您不需要花哨的设置来运行测试用例。只需设置几个从 main() 到您的函数的函数调用,然后在 for 循环中打印结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2017-12-22
    • 1970-01-01
    • 2021-07-02
    • 2015-08-25
    相关资源
    最近更新 更多