{
  "question_id": 756103,
  "question_title": "求分数数列的前N项和",
  "question_content": "有一分数序列:2/1,-3/2,5/3,-8/5,13/8,-21/13,…, 由用户输入项目数N，求这个数列的前N 项之和",
  "difficulty": "简单",
  "answer_id": 811223,
  "answer_content": "判断for循环的迭代变量即可。当迭代变量为偶数的时候，乘上一个-1。\n\n```\n#include<stdlib.h> \n#include<stdio.h>\nint main(){\n\tint n;\n\tscanf(\"%d\",&n);\n\t\n\tint i;\n\tdouble a1 = 2, b1 = 1;\n\tdouble a2 = 3, b2 = 2;\n\tdouble sum = a1/b1 - a2/b2;\n\t\n\tif(n==1) printf(\"%f\\n\",a1/b1);\n\telse if (n==2) printf(\"%f\\n\",sum);\n\telse{\n\t\tfor(i = 0;i<n-2;i++){\n\t\t\tdouble exp = a2 / b2;\n\t\t\tif(i%2==0) exp *= -1;\n\t\t\tsum += exp;\n\t\t\tdouble a = a1 + a2;\n\t\t\tdouble b = b1 + b2;\n\t\t\ta1 = a2;b1 = b2;\n\t\t\ta2 = a; b2 = b;\n\t\t}\n\t\tprintf(\"%f\\n\",sum);\n\t}\n\treturn 0;\n}\n\n```",
  "tag_name": "c语言",
  "cpp": "#include<stdlib.h> \n#include<stdio.h>\nint main(){\n\tint n;\n\tscanf(\"%d\",&n);\n\tint i;\n\tdouble a1 = 2, b1 = 1;\n\tdouble a2 = 3, b2 = 2;\n\tdouble sum = a1/b1 - a2/b2;\n\tif(n==1) printf(\"%f\\n\",a1/b1);\n\telse if (n==2) printf(\"%f\\n\",sum);\n\telse{\n\t\tfor(i = 0;i<n-2;i++){\n\t\t\tdouble exp = a2 / b2;\n\t\t\tif(i%2==0) exp *= -1;\n\t\t\tsum += exp;\n\t\t\tdouble a = a1 + a2;\n\t\t\tdouble b = b1 + b2;\n\t\t\ta1 = a2;b1 = b2;\n\t\t\ta2 = a; b2 = b;\n\t\t}\n\t\tprintf(\"%f\\n\",sum);\n\t}\n\treturn 0;\n}",
  "topic_link": "https://bbs.csdn.net/topics/600470268",
  "status": 1,
  "keywords": "算法初阶,基础知识,特征序列,概率分析和随机算法,概率分析和指示器随机变量的进一步使用",
  "license": "csdn.net",
  "notebook": {
    "cpp": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/answer/ipynb/cpp/83.ipynb?type=file"
  },
  "notebook_enable": 1,
  "author": "Skyiing"
}