{ "question_id": 7437073, "question_title": "编写递归函数和非递归函数", "question_content": "<p>编写一个递归函数和一个非递归函数,分别实现求1+2+3+...+n</p>", "difficulty": "简单", "answer_id": 53409711, "answer_content": "<p>代码如下,如有帮助,请采纳一下,谢谢。</p>\n\n<pre>\n<code>#include <stdio.h>\n//递归方法\nint sum(int n)\n{\n\tif(n == 1)\n\t\treturn 1;\n\telse\n\t\treturn n + sum(n-1);\n}\n\n//非递归方法\nint sum_2(int n)\n{\n\tint ss = 0;\n\tfor (int i = 1; i <=n;i++)\n\t{\n\t\tss += i; \n\t}\n\treturn ss;\n}\n\nint main()\n{\n\tint n;\n\tprintf("请输入n:");\n\tscanf("%d",&n);\n\t\n\tint s1 = sum(n);\n\tint s2 = sum_2(n);\n\tprintf("递归计算=%d;循环计算=%d\\n",s1,s2);\n\treturn 0;\n}</code></pre>\n\n<p> </p>\n", "tag_name": "c语言", "cpp": "#include <stdio.h>\nint sum(int n)\n{\n\tif(n == 1)\n\t\treturn 1;\n\telse\n\t\treturn n + sum(n-1);\n}\nint sum_2(int n)\n{\n\tint ss = 0;\n\tfor (int i = 1; i <=n;i++)\n\t{\n\t\tss += i; \n\t}\n\treturn ss;\n}\nint main()\n{\n\tint n;\n\tprintf(\"请输入n:\");\n\tscanf(\"%d\",&n);\n\tif(n == 0)\n\t\t{\n\t\t\tprintf(\"请输入正整数n\");\n\t\t\treturn -1;\n\t\t}\n\tint s1 = sum(n);\n\tint s2 = sum_2(n);\n\tprintf(\"递归计算=%d;循环计算=%d\\n\",s1,s2);\n\treturn 0;\n}", "topic_link": "https://bbs.csdn.net/topics/600470242", "status": 1, "keywords": "递归,算法", "license": "csdn.net", "notebook": { "cpp": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/answer/ipynb/cpp/1.ipynb?type=file" }, "notebook_enable": 1 }