递归加法(day1)
其他
2020-01-29 11:17:34
阅读次数: 0
题目:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C).
使用函数指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
typedef (*fun)(int);
int func1(int n) {
return
0;
}
int func2(int n) {
fun f[
2] = {func1, func2};
return n + f[(n !=
0)](n -
1);
}
void function1() {
cout << func2(
10) <<
endl;
}
|
使用静态变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
class test {
static
int N;
static
int sum;
public :
test() {
sum += ++N;
}
大专栏 递归加法(day1)lass="function">static void reset() {
N = sum =
0;
}
static int getSum() {
return sum;
}
};
int test::N =
0;
int test::sum =
0;
void function2() {
test::reset();
test *p =
new test[
10];
cout << test::getSum() <<
endl;
delete[]p;
}
|
使用虚函数的编译多态性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
class A {
public:
virtual int sum(int n) {
return
0; };
};
class B :
public A {
public:
int sum(int n) {
A a;
B b;
A *p[
2] = {&a, &b};
return n + p[(n -
1 !=
0)]->sum(n -
1);
}
};
void function3() {
B b;
cout << b.sum(
10) <<
endl;
}
|
源码github
转载自www.cnblogs.com/lijianming180/p/12239740.html