让函数返回错误代码
实例:范围限制
1 #include <iostream>
2 #include <climits>
3
4 using namespace std;
5 class Factorial
6 {
7 public:
8 Factorial(unsigned short num);
9 unsigned long getFactorial();
10 bool inRange();
11
12 private:
13 unsigned short num;
14 };
15 Factorial::Factorial(unsigned short num)
16 {
17 this->num = num;//传入的参数num值给了Factorial类中的属性num
18 }
19
20 unsigned long Factorial::getFactorial()
21 {
22 unsigned long sum = 1;
23 for(int i=1;i <= num; i++)
24 {
25 sum *= i;
26 }
27 return sum;
28 }
29 bool Factorial::inRange()
30 {
31 unsigned long max = ULONG_MAX;//ULONG_MAX在头文件climits中
32 for(int i = num; i >= 1; --i)//将最大值ULONG_MAX除以输入的num阶乘
33 {
34 max /= i;
35 }
36 if(max < 1)
37 return false;
38 else
39 return true;
40 }
41
42 int main()
43 {
44 unsigned short num = 0;
45 cout << "请输入一个整数:";
46 cin >> num;
47
48 Factorial fac(num);
49
50 if(fac.inRange())
51 {
52 cout << num << "的阶乘值是" << fac.getFactorial() << "\n\n";
53 }
54 else
55 {
56 cout << "您所输入的值太大!\n\n";
57 }
58 }