6.1.3 分离式编译

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qit1314/article/details/90137115

书中页数:P186
代码名称:LocalMath.h LocalMath.cc fact.cc

//LocalMath.h
#ifndef LOCALMATH_H
#define LOCALMATH_H

//definition in LocalMath.cc
int fact(int);        // iterative definition of factorial
int factorial(int);   // recrusive version of factorial
int gcd(int, int);    // find greatest common divisor
#endif
//LocalMath.cc
#include "LocalMath.h"

// return the greatest common divisor
int gcd(int v1, int v2)
{
    while (v2) {
        int temp = v2;
        v2 = v1 % v2;
        v1 = temp;
    }
    return v1;
}


// factorial of val is val * (val - 1) *  (val - 2) . . . * ((val -  (val - 1)) * 1)
int fact(int val)
{
	int ret = 1; // local variable to hold the result as we calculate it
	while (val > 1) 
		ret *= val--;  // assign ret * val to ret and decrement val
	return ret;        // return the result
}

// recursive version of factorial:
// calculate val!, which is 1 * 2 * 3 . . . * val
int factorial(int val)
{
    if (val > 1)
        return factorial(val-1) * val;
    return 1;
}
//fact.cc
#include <iostream>
using std::cout; using std::endl;

// declarations of our factorial functions
// definitions are in LocalMath.cc
#include "LocalMath.h"

int main()
{
	cout << factorial(5) << endl;
	cout << fact(5) << endl;
	cout << factorial(0) << endl;
	cout << fact(0) << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qit1314/article/details/90137115
今日推荐