用递归函数添加数字 [英] add numbers with recursive functions

查看:90
本文介绍了用递归函数添加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C,我想出了这个例子

I am learning C and i come up with this example

     #include <stdio.h>

     int MyAdd(int);
     main ()
     {
          int i;
          int c = 0;
          c = MyAdd(5); 
          printf("%d\n", c);
     }

     int MyAdd(int a)
     {
          if(a > 0)
               return a + MyAdd(--a);
          else
               return 0;
     }

我自己运行这个函数,我计算15.(5 +4 + 3 + 2 + 1)但是当我运行它,我得到10 ...为什么?
第一次,我们不再获得5+(再次做func)等等。?

I run this by my self and i calculate 15. (5 +4+3+2+1) but when i run it, i get 10... why??? At the 1st time, dont we get 5+ (do the func again) and etc..?

推荐答案

当在表达式中使用时,副作用操作符会做一些有趣的,意想不到的事情,因为基本上是由编译器支配的。

When used in expressions, side effect operators do funny, unexpected things, because you're basically at the mercy of the compiler.

在这种情况下,编译器正在评估在第一个操作数之前的 a + MyAdd( - a)>的第二个操作数。所以,在加法使用它之前,你要减少变量。

In this case, your compiler is evaluating the second operand of a + MyAdd(--a) before the first one. So, you're decrementing the variable before using it in the addition.

在任何情况下,你都不需要减量运算符。我建议将该行重写为 return a + MyAdd(a - 1);

In any case, you don't really need the decrement operator. I would suggest rewriting the line as return a + MyAdd(a - 1);.

这篇关于用递归函数添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆