2017-10-20 75 views
1

我想知道如何让一个函数考虑一个给定的参数作为一个静态变量。例如,我试过,没有成功,生成hailstone号码:精心设计一个函数参数作为静态变量

#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上运行,因此会持续不断,从未达到案例库。

几个问题:

  1. 这是否代表想法可行的问题解决办法?
  2. 这个想法是否代表合理/有效的方法来解决问题?
  3. 是否exit(0)使用正确,类似的情况?
+2

'静态INT米;然而,m = n;'是可能的。 – Bathsheba

+3

在递归函数中使用全局变量会挫败递归的重点,所以您肯定需要重新考虑您的解决方案。在任何情况下,你的函数都不会显示任何基本情况(除0以外,无法达到)。在你看来,基本情况是什么?为什么你认为递归不能达到它? – rici

+0

@ricie,是不是'm <1'表示的案例库?也许,因为最终的结果应该是1,'m == 1'可能是更好的基本情况,你是对的。另外,我正在徘徊在如何超越全球变量的问题上。 – Worice

回答

3

你不需要一个静态变量。只要通过新的价值来操作和使用它。此外,值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; 
     } 
    } 
} 
+0

感谢@rici评论我调整了案例库,谢谢。 – Worice

+1

我会对你的代码做一点练习。感谢这个双重例子。递归对我来说仍然不是那么直观,因此能够将它与迭代方法进行比较是非常有用的。 – Worice

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); 
} 
+0

感谢你的例子,它给了我一个很好的洞察问题! – Worice