我想將此非遞回函式轉換為遞回函式。我該怎么做?我必須找到能被 7 整除的 2 個數字之間的數字個數。
void count_divisors2(int min, int max) {
//Variable to store the counter
int counter = 0, i;
// Running a loop from A to B and check
// if a number is divisible by M.
for (i = min; i <= max; i ) {
if (i % 7 == 0)
counter ;
}
printf("%d", counter);
}
uj5u.com熱心網友回復:
您應該回傳計數而不是列印數字:
非遞回版本:
int count_divisors2(int min, int max) {
//Variable to store the counter
int counter = 0, i;
// Running a loop from A to B and check
// if a number is divisible by M.
for (i = min; i <= max; i ) {
if (i % 7 == 0)
counter ;
}
return counter;
}
遞回版本:
int count_divisors2(int min, int max) {
if (min > max)
return 0;
else
return (min % 7 == 0) count_divisors2(min 1, max);
}
直接版:
int count_divisors2(int min, int max) {
if (min <= max) {
if (min >= 0)
return (max / 7) - (min / 7) (min % 7 == 0);
else
if (max >= 0)
return (max / 7) - (min / 7) 1;
else
return (max / 7) - (min / 7) (max % 7 == 0);
} else {
return 0;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403057.html
標籤:
上一篇:如何遞回映射/重組物件?
