有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和.怎么做啊?求大虾帮忙啊!
有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和.怎么做啊?求大虾帮忙啊!
#include<stdio.h> #include<math.h> #define sqrt_5 2.2360679774997896964091736687313 #define A ((1 + sqrt_5) / 2) #define B ((1 - sqrt_5) / 2) #define C (B / A) double f(int n) { double a, p; p = pow(C, n + 1); a = (A - B * p) / (1 - p); return a; } int main() { int i; double a; for(a = 0, i = 1; i <= 20; a += f(i++)); printf("%f\n", a); return 0; }
#include <assert.h> #include <stdio.h> typedef enum { M_DATA, D_DATA } TYPE_E; int get_data(int n, TYPE_E type) { int op1, op2; int i; assert(n > 0); if (n == 1) return ((type == M_DATA) ? 2 : 1); for (i = 1, op1 = 1, op2 = 2; i < n; i++) { op1 = op2 | ((op1 + op2)<<16); op2 = (op1>>16) & 0xffff; op1 &= 0xffff; } return ((type == M_DATA) ? op2 : op1); } float md(int m, int d) { assert(m > d); if (m == 2 && d == 1) return (float)2; else return (((float)m/(float)d) + md(d, m - d)); } int main(int argc, char *argv[]) { printf("result = %f\n", md(get_data(20, M_DATA), get_data(20, D_DATA))); return 0; }应该写的挺干净的