斐波那契数列

时间:2019-04-20 13:47:53   收藏:0   阅读:128
#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; }

原文:https://blog.51cto.com/frankniefaquan/2381774

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!