Home 數學運算 (中文)
Post
Cancel

數學運算 (中文)

數學運算相關 header

這邊介紹一下標準庫與數學運算相關的內容,主要為 <numeric> <numbers> <cmath> header。

特別講一下 <numbers> , 它提供了很多常用的常數,這樣我們就不用自己去定義。

最怕在 code 中看到有人去定義 Pi 之類的常數,因為根本不知道到底從哪邊抄來的,如果在大型專案中,這類的常數定義還不只一個,簡直是災難阿。

標準庫有定義了,大家都使用標準庫的定義最安全。

and

這兩個 header 是 c++17 以上提供。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <numeric>
#include <numbers>

 int main()
 {
     constexpr auto lcm = std::lcm(10, 5); // 最小公倍數
     std::cout << "lcm: " << lcm << std::endl;

     constexpr auto gcd = std::gcd(20, 15); // 最大公因數
     std::cout << "gcd: " << gcd << std::endl;

     std::cout << "Pi: " << std::numbers::pi << std::endl;
     std::cout << "Euler's number (e): " << std::numbers::e << std::endl;
     std::cout << "Log base 2 of e: " << std::numbers::log2e << std::endl;
     std::cout << "Square root of 2: " << std::numbers::sqrt2 << std::endl;

     return 0;
 }

其中 <numbers> 還有以下常數可以使用

Desktop View

<cmath> 提供了多種數學運算函數,涵蓋基礎的數學運算、三角函數、對數、指數等,以下是這些函數的簡介:

  1. 絕對值與符號處理 std::abs(x):計算 x 的絕對值,適用於整數與浮點數。 std::fabs(x):專門計算浮點數 x 的絕對值。 std::signbit(x):檢查 x 是否為負數,返回布林值。 std::copysign(x, y):返回與 x 絕對值相同,但符號與 y 相同的值。
  2. 冪次與根號運算 std::pow(x, y):計算 x 的 y 次方。 std::sqrt(x):計算 x 的平方根。 std::cbrt(x):計算 x 的立方根。 std::hypot(x, y):計算直角三角形的斜邊長,即 sqrt(xx + yy)。
  3. 指數與對數運算 std::exp(x):計算 e 的 x 次方。 std::log(x):計算 x 的自然對數(底數為 e)。 std::log10(x):計算 x 的常用對數(底數為 10)。 std::log2(x):計算 x 的二進位對數(底數為 2)。
  4. 三角函數 std::sin(x):計算 x 的正弦值。 std::cos(x):計算 x 的餘弦值。 std::tan(x):計算 x 的正切值。 std::asin(x):計算 x 的反正弦值(弧度)。 std::acos(x):計算 x 的反餘弦值(弧度)。 std::atan(x):計算 x 的反正切值(弧度)。 std::atan2(y, x):計算由原點至點 (x, y) 的角度。
  5. 舍入與取整 std::ceil(x):將 x 向上取整。 std::floor(x):將 x 向下取整。 std::round(x):將 x 四捨五入。 std::trunc(x):截斷 x 的小數部分,僅保留整數部分。
  6. 其他常用函數 std::fmod(x, y):計算 x 除以 y 的餘數。 std::modf(x, intpart):將 x 分解為整數和小數部分,返回小數部分。 std::frexp(x, exp):將 x 分解為尾數與指數部分,返回尾數,並將指數存入 exp 中。 std::ldexp(x, exp):計算 x * 2^exp。

這邊只是列出常用的,想看更完整資訊可以看 cppreference

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍