斐波纳锲数列:
fab.h
#pragma once
#include <iostream>
#include <string>
template <typename T>
T fab(T n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fab(n - 1) + fab(n - 2);
}
template <typename T>
class fabObj {
public:
T operator()(T n) {
if (n == 0) return 0;
if (n == 1) return 1;
T val = fab(n - 1) + fab(n - 2);
std::cout << "The number is: " << n;
std::cout << ", the value is: " << val << std::endl;
return val;
}
};
main.cpp
#include <vector>
#include <algorithm>
#include "fab.h"
using namespace std;
int main() {
fabObj<int> f;
vector<int> v{1,2,3,4,5,6,7,8,9};
for_each(v.begin(), v.end(), f);
}
The number is: 2, the value is: 1
The number is: 3, the value is: 2
The number is: 4, the value is: 3
The number is: 5, the value is: 5
The number is: 6, the value is: 8
The number is: 7, the value is: 13
The number is: 8, the value is: 21
The number is: 9, the value is: 34