www.rtmj.net > 用递归求1到100的和python

用递归求1到100的和python

int func(int num) { int sum; if (num > 1) sum = num + func(num-1); else sum = 0; return sum; } void main() { int sum = func(100); printf("the sum of 1 to 100 is %d", sum); return; }

i = 1sum = 0while i <= 100: sum += sum + i i += i +1 print(sum + ", ", end="") 需注意两点一、输出sum python2用 :print sum Python3用:print(sum) 二、脚本运行环境的不同会有一些差别 例如在Python自带的idle 中运行 和在cmd命令下运行 有细微差别

public class test { public static int sum(int s){ if(s==0) return 0; else return s+sum(--s); //递归体现在这里 } public static void main(string[] args) { system.out.println(sum(100));//打印计算的结果 } }

num = 0 for i in range(1,101): num += i print num

##第一种方法 a = 0 for i in range(0,100): a += (i+1); print a##第二种方法 sum(range(1,101))##第三种方法 sum([ x for x in range(0,101)])

#include using namespace std; int sum(int max); int main() { cout1){ return max+sum(max-1); }else{ return 1; } }

#include&lt;stdio.h&gt;#include&lt;math.h&gt;long AddOdd(long nNum){ if (nNum&lt;1) return 0; else if (nNum==1) return 1; else return nNum + AddOdd(nNum-2);}void main(){ printf("Sum = %d\n", AddOdd(99));}

public static void main(String args[]){ int sum=0; for(int i=1;i<=100;i++){ sum+=i; } System.out.println(sum); }

def factorial(n):if n <= 1:return 1else:return n * factorial(n - 1)the_range = range(1, 100)the_list = [factorial(a) for a in the_range]sum = reduce(lambda x,y: x+y, the_list)print sum

int sum(int s){ if(s > 2) { s = sum(s-1) + s ; } else { s = s + 1 ; } return s ;}这是java的,不过其他语言大同小异1、有自我调用2、有出口3、有返回值基本上递归就写好了

网站地图

All rights reserved Powered by www.rtmj.net

copyright ©right 2010-2021。
www.rtmj.net内容来自网络,如有侵犯请联系客服。zhit325@qq.com