[英]Elaborate a function parameter as static variable
我想知道如何使函數將給定參數視為靜態變量。 例如,我嘗試生成冰雹數字但沒有成功:
#include<stdio.h>
int hailstone(int);
int n; /* n is an extern variable*/
int main(){
hailstone(n);
return 0;
}
int hailstone(int n){
static int m = n; /*not possible because n is not constant*/
if(m % 2 == 0 && m != 1)
hailstone(m /= 2);
else if(m != 1)
hailstone((m *= 3) + 1);
else
exit(0); /*Is the use of exit() correct, in this case?*/
return 0;
}
我想使用一個靜態變量來詳細說明n。 否則,每個遞歸調用都將對整個參數n
,從而進行無休止的處理,永遠不會到達案例庫。
幾個問題:
exit(0)
是否正確使用? 為此,您不需要靜態變量。 只需傳遞新值即可繼續使用。 另外,值1是您的基本情況,因此請檢查該值以停止遞歸,並打印值n
以便您可以實際看到正在發生的情況。
void hailstone(int n){
printf("n=%d\n", n);
if(n % 2 == 0 && n > 1) {
hailstone(n/2);
} else if(n > 1) {
hailstone((n*3) + 1);
}
}
鑒於此功能可以進行多次迭代,因此遞歸解決方案最終可能導致堆棧溢出。 最好使用迭代解決方案:
void hailstone(int n){
while (n > 1) {
printf("n=%d\n", n);
if(n % 2 == 0) {
n = n/2;
} else {
n = (n*3) + 1;
}
}
}
這是冰雹的遞歸算法,不需要static
#include <assert.h>
#include <stdio.h>
void hailstone(unsigned int n)
{
assert(n>0);
printf("%u\n", n);
if ( n == 1 )
return;
if( n & 1 ) {
hailstone(3*n + 1);
}
else {
hailstone(n >> 1);
}
}
int main() {
hailstone(5);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.