{
  "question_id": 7437073,
  "question_title": "编写递归函数和非递归函数",
  "question_content": "<p>编写一个递归函数和一个非递归函数&#xff0c;分别实现求1&#43;2&#43;3&#43;...&#43;n</p>",
  "difficulty": "简单",
  "answer_id": 53409711,
  "answer_content": "<p>代码如下&#xff0c;如有帮助&#xff0c;请采纳一下&#xff0c;谢谢。</p>\n\n<pre>\n<code>#include &lt;stdio.h&gt;\n//递归方法\nint sum(int n)\n{\n\tif(n &#61;&#61; 1)\n\t\treturn 1;\n\telse\n\t\treturn n &#43; sum(n-1);\n}\n\n//非递归方法\nint sum_2(int n)\n{\n\tint ss &#61; 0;\n\tfor (int i &#61; 1; i &lt;&#61;n;i&#43;&#43;)\n\t{\n\t\tss &#43;&#61; i; \n\t}\n\treturn ss;\n}\n\nint main()\n{\n\tint n;\n\tprintf(&#34;请输入n&#xff1a;&#34;);\n\tscanf(&#34;%d&#34;,&amp;n);\n\t\n\tint s1 &#61; sum(n);\n\tint s2 &#61; sum_2(n);\n\tprintf(&#34;递归计算&#61;%d;循环计算&#61;%d\\n&#34;,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,
  "author": "weixin_45128830"
}