标签:斐波那契数 except std else index pre i++ ++i row
#include<iostream>
#include<exception>
int fibnaci(int index) {
try {
if (index >= 0) {
int arr[3] = { 1, 1, 0 };
for (int i = 2; i <= index; ++i) {
arr[2] = arr[0] + arr[1];
arr[0] = arr[1];
arr[1] = arr[2];
}
return index < 2 ? arr[index] : arr[2];
}
else {
throw std::invalid_argument("index < 0");
}
}
catch (std::exception &e) {
std::cout << "exception:" << e.what() << std::endl;
return -1;
}
}
int main()
{
for (int i = 0; i < 15; i++) {
std::cout << fibnaci(i) << "\t";
}
std::cout << std::endl;
system("pause");
std::cout << fibnaci(-1) << std::endl;
system("pause");
return 0;
}
标签:斐波那契数 except std else index pre i++ ++i row
原文地址:https://blog.51cto.com/frankniefaquan/2381774