kainster

never too late
posts - 33, comments - 3, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

递归函数中慎用宏

Posted on 2008-10-21 17:18 kainster 阅读(159) 评论(0)  编辑  收藏

#include <iostream>
#include <time.h>
using namespace std;
#define NUM 27
#define max(a,b) ((a) > (b) ? (a) : (b))

float x[NUM];
//float max(float num1, float num2)
//{
// return num1 > num2 ? num1 : num2;
//}
float arrmax(int n)
{
 if( n == 1)
  return x[0];
 else
  return max( x[n-1], arrmax(n-1));
}
int main()
{
 for( int i=0; i<NUM; i++ )
  x[i] = rand();

 cout << arrmax( NUM ) <<endl;
 cout << "The calculation costs "<< clock() <<" ticks" << endl;
}
用宏的话一分钟都算不出来结果,但是如果用函数连一秒都不用
因为用宏的话会把
max( x[n-1], arrmax(n-1))
替换成
x[n-1] > arrmax(n-1) ?  x[n-1] : arrmax(n-1)
这样arrmax的执行次数就翻倍了,然后再一递归,时间翻的倍数就更多了


只有注册用户登录后才能发表评论。


网站导航: