在本教程中,我们将讨论一个程序来查找系列1、1、2、3、4、9、8、27、16、81、32、243、64、729、128、2187的第N个项…
为此,我们将使用整数N。我们的任务是计算并打印序列中第N个位置的项。
#include <iostream>
#include <math.h>
using namespace std;
//在给定系列中找到第n个项
void findNthTerm(int n) {
//如果甚至
if (n % 2 == 0) {
n = n / 2;
cout << pow(3, n - 1) << endl;
}
//如果是奇数
else {
n = (n / 2) + 1;
cout << pow(2, n - 1) << endl;
}
}
int main() {
int N = 4;
findNthTerm(N);
N = 11;
findNthTerm(N);
return 0;
}输出结果
3 32