[英]How to count the number of 0's in array using recursion?
下面是我使用的代碼。 它返回 0 作為計數。這里的錯誤原因是什么?基本條件不合適嗎?
#include<bits/stdc++.h>
using namespace std;
int CountZeros(int a[], int n, int count) {
int i = 0;
//base condition
if (n == 0) return 0;
if (a[0] == 0) {
count += 1;
}
int SmallAns = CountZeros(a + 1, n - 1, count);
}
int main() {
int count = 0;
int a[5] = {
1,
0,
3,
0,
5
};
CountZeros(a, 5, count);
cout << count;
return 0;
}
您的 function 在遞歸情況下不會返回任何內容,從而導致未定義的行為。
(遞歸函數的工作方式與非遞歸函數完全一樣——如果您不return
值,則不會返回任何值。)
您的目標似乎是尾遞歸,在這種情況下,基本情況應該返回累積參數( count
),而不是基值,並且您使用基值(零)進行初始調用:
int CountZeros(int a[], int n, int count) {
if (n == 0)
return count;
else
return CountZeros(a + 1, n - 1, a[0] == 0 ? count + 1 : count);
}
使用非尾遞歸,您不會將count
作為參數傳遞,而是添加到遞歸結果中:
int CountZeros(int a[], int n) {
if (n == 0)
return 0;
int SmallAns = CountZeros(a + 1, n - 1);
return a[0] == 0 ? SmallAns + 1 : SmallAns;
}
不過,這效率較低——一個體面的編譯器會將尾遞歸版本轉換為一個簡單的循環(gcc、clang 和 msvc 都這樣做)。
第一個任務,當n
等於 0 時,正確的返回值是count
not 0
。 即你已經到達數組的末尾,所以你必須返回到目前為止你計算的所有零。 這是必要的,因為您在遞歸調用之前添加了計數。
if (n == 0) return count;
另一方面,如果您在遞歸調用之后添加到計數,則return 0;
是正確的。
第二個任務,在您進行遞歸調用后,實際上從CountZeros
function 返回一些東西。
int SmallAns = CountZeros(a + 1, n - 1, count);
return SmallAns;
第三個任務,在main
function 中使用該返回值
count = CountZeros(a, 5, count);
cout << count;
現在,可選的第四個任務,這段代碼中有很多不需要的變量。 看看您是否可以刪除main
中的count
變量以及CountZeros
中的smallAns
和i
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.