forked from mcpp-community/d2mcpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07-constexpr-1.cpp
More file actions
73 lines (58 loc) · 1.87 KB
/
07-constexpr-1.cpp
File metadata and controls
73 lines (58 loc) · 1.87 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// mcpp-standard: https://github.com/Sunrisepeak/mcpp-standard
// license: Apache-2.0
// file: dslings/cpp11/07-constexpr-1.cpp
//
// Exercise/练习: cpp11 | 07 - constexpr | 编译期计算应用示例
//
// Tips/提示: 根据编译器的输出, 修复编译器报错
//
// Docs/文档:
// - https://en.cppreference.com/w/cpp/language/constexpr
//
// Auto-Checker/自动检测命令:
//
// d2x checker constexpr
//
#include <d2x/common.hpp>
#include <iostream>
template <int N>
struct Sum {
static constexpr int value = Sum<N - 1>::value + N;
};
template <>
struct Sum<1> { static constexpr int value = 1; };
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
double pow(double base, int exp) {
return exp == 0 ? 1.0 : base * pow(base, exp - 1);
}
constexpr double mysin(double x) {
//constexpr double PI = 3.14159265358979323846;
//constexpr double radius = x * PI / 180.0;
#define radius(x) (x * 3.14159265358979323846 / 180.0)
// (-1)^n * radius(x)^2n+1 / factorial(2n + 1);
return radius(x)
- pow(radius(x), 3) / factorial(3)
+ pow(radius(x), 5) / factorial(5);
}
int main() {
// 1. 编译期-函数计算
constexpr int fact_10 = factorial(10);
std::cout << "1 * 2 * .. * 10 = " << fact_10 << std::endl;
// 2. 编译期-模板参数计算
constexpr int sum_4 = Sum<4>::value;
std::cout << "1 + 2 + 3 + 4 = " << sum_4 << std::endl;
// 3. 编译期计算示例:
// value是多少时? value! + (1 + 2 + .. + value) > 10000
constexpr int value = 5;
int f = factorial(value);
constexpr int s = Sum<value>::value;
constexpr int ans = f + s;
static_assert(ans > 10000);
// 4. 编译期计算sin值(自动打表) - 时间复杂度O(1)
constexpr double sin30 = mysin(30.0);
std::cout << "mysin(30): " << sin30 << " " << std::endl;
D2X_WAIT
return 0;
}