// 程序仅在VS7.0下通过。
/*
1. 编写重载函数Max1可分别求取两个整数,三个整数,
两个双精度数,三个双精度数的最大值。
*/
#include <iostream>
using namespace std;
double Max1 (double a,double b)
{
return (a>b)?a:b;
}
double Max1 (double a,double b,double c)
{
return (a>b?a:b)>c?(a>b?a:b):c;
}
void main()
{
cout << Max1(15,10) << endl;
cout << Max1(45,30,20) << endl;
cout << Max1(2.3,2.5) << endl;
cout << Max1(4.5,3.0,2.8) << endl;
}
// 清翔兔
// 05/10/26
// 程序仅在VS7.0下通过。
/*
2. 设计评测内联函数的效率:设计一个程序,
比较直接运行语句(i>j)? i:j; 与运行内联函数和运行外部函数之间的所耗时间。
三者分别运行1000000 次。i与j 循环变化。
再将内联函数或外部函数设计得复杂一点:
如添上相同的五条语句,分别比较三者的时间消耗。
*/
#include <time.h>
#include <iostream>
using namespace std;
void f1(int i, int j) { (i>j)?i:j; }
inline void f2(int i, int j) { (i>j)?i:j; }
double gettime()
{
clock_t t;
double time;
t = clock();
if ((clock_t)-1 == t)
return -1; /* 调用失败,退出 */
time = (double)t / CLOCKS_PER_SEC; /* 转换成秒 */
return time;
}
void main ()
{
double beginning_time, finish_time;
int i=0,j=0;
// 发现7.0下编译之后,需要10000000000000次,才有明显结果
beginning_time = gettime();
for (; i<1000000 ; i++)
for (; j<1000000 ; j++)
(i>j)?i:j;
finish_time = gettime();
cout << "直接:" << finish_time - beginning_time << endl;
beginning_time = gettime();
for (i=0; i<1000 ; i++)
for (j=0; j<10000 ; j++)
f1(i,j);
finish_time = gettime();
cout << "函数:" << finish_time - beginning_time << endl;
beginning_time = gettime();
for (i=0; i<1000 ; i++)
for (j=0; j<10000 ; j++)
f2(i,j);
finish_time = gettime();
cout << "内联:" << finish_time - beginning_time << endl;
}
// 清翔兔
// 05/10/26
// 程序仅在VS7.0下通过。
/*
3.设计一个求和函数Sum,函数原型为Sum( int num ...) ,
其中第一个参数是表示后面将出现的参数个数.
后面跟着是若干个整型参数(个数不确定).
该函数可以对函数调用时出现在参数num后面的若干个整型实参进行求和并返回结果.
例如该函数的调用形式可能是:Sum(3, 30 , 27, 45 ).
*/
#include <stdarg.h>
#include <iostream>
using namespace std;
int Sum( int num ...)
{
va_list ap;
va_start(ap,num);
int sum = 0;
for ( int i=0 ; i< num ; i++)
{
int a = va_arg( ap ,int );
sum += a;
}
va_end(ap);
return sum;
}
void main()
{
cout << Sum(3, 30, 27, 45) << endl;
}
// 清翔兔
// 05/10/26
// 程序仅在VS7.0下通过。
/*
4. 运行教材P99-100的关联数组的实例,
理解函数返回值为引用类型的使用。
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Pair {
string name;
double val;
};
vector<Pair> pairs;
double& value (const string& s)
{
for ( unsigned int i=0; i < pairs.size(); i++)
if (s==pairs[i].name) return pairs[i].val;
Pair p = {s,0};
pairs.push_back(p);
return pairs[pairs.size()-1].val;
}
int main()
{
string buf;
while (cin >> buf) value(buf)++;
for (vector<Pair>::const_iterator p=pairs.begin(); p!=pairs.end(); ++p)
cout << p->name << ": " << p->val << '/n';
}
// 书本实例