基本上,它在發生時只列印一個實體,我不明白為什么,可能與每次重置代碼并再次從 0 開始變數有關,如果有人可以幫助我,我還有另一個問題,我必須在奇數和偶數時回傳這兩個值,例如有多少位數字同時是偶數和奇數,我在弄清楚如何做時遇到了一些麻煩
#include <stdio.h>
int digits(int n)
// function that checks if the given value is odd or even, and then add
// 1 if it's even, or odd, it's supposed to return the value of the quantity
// of digits of the number given by the main function
{
int r;
int odd = 0;
int even = 0;
r = n % 10;
if (r % 2 == 0) // check if given number is even
{
even = even 1;
}
if (r % 2 != 0) // check if its odd
{
odd = odd 1;
}
if (n != 0) {
digits(n / 10); // supposed to reset function if n!=0 dividing
// it by 10
}
if (n == 0) { return odd; }
}
int
main() // main function that sends a number to the recursive function
{
int n;
printf("type number in:\n ");
scanf("%d", &n);
printf("%d\n", digits(n));
}
uj5u.com熱心網友回復:
odd和even變數在您的代碼中是區域的,因此它們每次都被初始化為零。我認為它們應該在遞回函式的呼叫者處宣告,或者宣告為全域變數。
#include <stdio.h>
void digits(int n, int *even, int *odd)//function
{
int r;
r = n % 10;
if (r % 2 == 0)//check if given number is even
{
*even = *even 1;
}
else //otherwise, its odd
{
*odd = *odd 1;
}
n /= 10;
if (n != 0)
{
digits(n, even, odd);//supposed to reset function if n!=0 dividing it by 10
}
}
int main()
{
int n, even = 0, odd = 0;
printf("type number in:\n ");
scanf("%d", &n);
digits(n, &even, &odd);
printf("even: %d\n", even);
printf("odd: %d\n", odd);
return 0;
}
uj5u.com熱心網友回復:
也許我發現了你面臨的問題。您將奇數和偶數變數初始化為零。每次呼叫該函式時,它都會再次將它們的值重新宣告為零。您可以使用指標呼叫者或將它們用作全域變數,以便每次它們都不會再次重復其初始值。
uj5u.com熱心網友回復:
實作一個計算數字中奇數和偶數位數的函式,不能使用 recursive 來完成。這簡直是??一個錯誤的設計選擇。
但我認為使用遞回是你任務的一部分,所以......好吧。
您需要一個可以回傳兩個值的函式。好吧,在 C 中你不能!!C 只允許一個回傳值。所以你需要另一種方法。典型的解決方案是將指標傳遞給要存盤結果的變數。
這是代碼:
void count_odd_even(const int n, int *even, int *odd)
{
if (n == 0) return;
if (((n % 10) % 2) == 1)
{
*odd = 1;
}
else
{
*even = 1;
}
count_odd_even(n/10, even, odd);
}
并稱之為
int odd = 0;
int even = 0;
count_odd_even(1234567, &even, &odd);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359889.html
上一篇:在c中,這個引數是什么意思`myfunc(mystruct_t*const*pVar)`?
下一篇:最長公共后綴產生垃圾值
