就拿怎么求两个数的最大公约数举例子吧。
定义一个函数,
- int greatestCommonDivisor(int a, int b) {
- const int minNum = (a < b) ? a : b;
- for (int i = minNum; i >= 1; i--) {
- if (a%i ==0 && b%i ==0 ){
- return i;
- }
- }
- return 1;
- }
引入Window.h头文件,调用函数之前
DWORD startTime = GetTickCount();//计时开始
调用函数之后
DWORD endTime = GetTickCount();//计时开始
最后两个时间相减就得到了程序的运行时间。
完整代码如下:
- #include
- #include
- using namespace std;
-
- int greatestCommonDivisor(int a, int b);
- //暴力枚举
- int greatestCommonDivisor(int a, int b) {
- const int minNum = (a < b) ? a : b;
- for (int i = minNum; i >= 1; i--) {
- if (a%i ==0 && b%i ==0 ){
- return i;
- }
- }
- return 1;
- }
- }
-
- int main() {
-
- int a;
- int b;
- cout << "请输入a的值" << endl;
- cin >> a;
- cout << "请输入b的值" << endl;
- cin >> b;
- //计时开始
- DWORD startTime = GetTickCount();
- int x = greatestCommonDivisor(a, b);
- //计时结束
- DWORD endTime = GetTickCount();
- cout << "The run time is:" << endTime - startTime << "ms" << endl;
- cout << "最大公约数为:" << x << endl;
- return 0;
-
- }