簡體   English   中英

C 程序使用 2 計算數字中的每個數字 Arrays

[英]C Program To Count Each Digit In A Number using 2 Arrays

我需要編寫一個名為void digits (int arr [], int size, int statistics [])的 function,它接收一個整數數組及其大小,以及另一個數組,稱為統計數據,大小為 10。function更改數組統計信息,使其包含數組數組的數字中每個告訴的印象數。 也就是說,statistics [i]包含了故事 i 的出現次數。 function 不會更改“ arr ”數組,也不會打印任何內容。 例如,如果arr [] = {438,439,440,441,442,443,444}那么在 function 運行的末尾statistics [] = {1,1,1,3,13,0,0,0,1,1} 即數字0在“arr”數組中出現一次,數字1在“arr”數組中出現一次,以此類推。

您應該使用 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) ;
  }
}

為您的代碼編寫測試用例也是一個好習慣,對於像這樣的快速破解,您不需要花哨的設置來運行測試用例。 只需設置幾個 function 從main()調用到您 function 並在 for 循環中打印結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM