c++某一数列的前2项为a与b根据选项t1—等差数列2—等比数列3—类斐波那契数列计算此数列第n项的值使用以下主函数调用的方式完成。int main int a b n t; cin a b n t; cout figurea b n t;
#include
int figure(int a, int b, int n, int t) { int c; if(t==1) { // 等差数列 int d = b-a; c = a + (n-1)*d; } else if(t==2) { // 等比数列 double q = double(b)/a; c = a * pow(q, n-1); } else if(t==3) { // 类斐波那契数列 if(n==1) c = a; else if(n==2) c = b; else { int pre1 = a, pre2 = b, now; for(int i=3; i<=n; i++) { now = pre1 + pre2; pre1 = pre2; pre2 = now; } c = now; } } return c; }
int main() { int a, b, n, t; cin >> a >> b >> n >> t; cout << figure(a, b, n, t); return 0;
原文地址: https://www.cveoy.top/t/topic/eeFp 著作权归作者所有。请勿转载和采集!