• 4026阅读
  • 3回复

一段C++代码求改…… [复制链接]

上一主题 下一主题
离线mewjerry
 
只看楼主 倒序阅读 楼主  发表于: 2010-04-09

最近看模板元编程,就很想比较一下各种形式代码的效率,所以写了三段生成斐波那契数列的代码,分别是用while循环、函数嵌套、模板元。
结果还是出错了- -||

第一个方法是能够得到结果的(虽然int不够放后面的数的……
第二个方法看着命令行狂跳一段时间之后,居然自动关闭了,纳闷,我明明写了getchar()为什么还会自动关闭呢?可能出现了错误,但不知道在哪,求解……
第三个方法编译能够通过,但是输出只有1和0,背离了预期,也不知道是为什么。以前没用过模板,求解……
  1. //方法一
  2. #include <iostream>
  3. using namespace std;
  4. /*
  5. int main()
  6. {
  7. int a=0,b=1,i=0;
  8. while(i<500)
  9. {
  10. cout<<a<<","<<b<<",";
  11. a=a+b;
  12. b=a+b;
  13. i++;
  14. }
  15. getchar();
  16. }
  17. */


  1. #include <iostream>
  2. using namespace std;
  3. //方法二
  4. void Feb(int a=0,int b=1,int i=500)
  5. {
  6. if(i=0)  return;
  7. cout<<a<<","<<b<<",";
  8. a=a+b;
  9. b=a+b;
  10. i--;
  11. Feb(a,b,i);
  12. }
  13. int main()
  14. {
  15. Feb();
  16. getchar();
  17. }


  1. //方法三
  2. #include <iostream>
  3. using namespace std;
  4. template <int i>
  5. class Feblar
  6. {
  7. public:
  8. static void Feb(int a=0,int b=1)
  9. {
  10. cout<<a<<","<<b<<",";
  11. Feblar<i-1>::Feb(a,b);
  12. }
  13. };
  14. template<>
  15. class Feblar<0>
  16. {
  17. public:
  18. static void Feb(int a,int b)
  19. {
  20. }
  21. };
  22. int main()
  23. {
  24. Feblar<500>::Feb();
  25. getchar();
  26. }
离线mewjerry
只看该作者 1楼 发表于: 2010-04-09
- -||居然被完全无视了,上顶下求解……
离线steinlee

只看该作者 2楼 发表于: 2010-04-09
When possible, do not use recursive code because recursive methods use a lot of stacks. On Windows the size of stack use is limited.
It is so easy to write a for loop for this kind of things.
[ 此帖被steinlee在2010-04-09 23:42重新编辑 ]
Looking for remote C/C++ and Qt 兼职
离线mewjerry
只看该作者 3楼 发表于: 2010-04-14
算了- -我自己更正了。最后放出正确的来:

  1. #include <iostream>
  2. using namespace std;
  3. //////////////////////////////////////
  4. //方法一
  5. /*
  6. int main()
  7. {
  8. int a=0,b=1,i=0;
  9. while(i<20)
  10. {
  11. cout<<a<<","<<b<<",";
  12. a+=b;
  13. b+=a;
  14. i++;
  15. }
  16. getchar();
  17. }
  18. */
  19. //////////////////////////////////////
  20. //方法二
  21. /*
  22. void Feb(int & a,int & b,int & i)
  23. {
  24. if(i==0)  
  25.   return ;
  26. cout<<a<<","<<b<<",";
  27. a+=b;
  28. b+=a;
  29. Feb(a,b,--i);
  30. }
  31. int main()
  32. {
  33. int a0=0,b0=1,i=20;
  34. Feb(a0,b0,i);
  35. getchar();
  36. return 0;
  37. }
  38. */
  39. //////////////////////////////////////
  40. //方法三
  41. /*
  42. template <int i>
  43. class Feblar
  44. {
  45. public:
  46. static void Feb(int a=0,int b=1)
  47. {
  48. cout<<a<<","<<b<<",";
  49. a+=b;
  50. b+=a;
  51. Feblar<i-1>::Feb(a,b);
  52. }
  53. };
  54. template<>
  55. class Feblar<0>
  56. {
  57. public:
  58. static void Feb(int a,int b)
  59. {
  60. }
  61. };
  62. int main()
  63. {
  64. Feblar<20>::Feb();
  65. getchar();
  66. }  
  67. */
  68. //////////////////////////////////////
快速回复
限100 字节
 
上一个 下一个