C++ 提供豐富的基本數值型別:int、short、long、float、double 等,其範圍與精度依實作定義(參考 <climits>/<cfloat>)。
#include <iostream>
using namespace std;
int main() {
short s = 10;
int i = 1000;
long l = 1000000;
float f = 230.47f;
double d = 30949.374;
cout << "short: " << s << endl;
cout << "int: " << i << endl;
cout << "long: " << l << endl;
cout << "float: " << f << endl;
cout << "double: " << d << endl;
return 0;
}
<cmath>包含標準數學函式,引數與回傳值多為 double。常用函式:
| 函式 | 說明 |
|---|---|
sin, cos, tan | 三角函式(弧度制) |
asin, acos, atan, atan2 | 反三角函式 |
exp, log, log10 | 指數、自然對數、常用對數 |
pow(x, y) | x 的 y 次方 |
sqrt(x) | 平方根 |
hypot(x, y) | √(x²+y²),直角三角形斜邊 |
abs(int) / fabs(double) | 絕對值 |
floor, ceil, round | 向下/向上/四捨五入取整 |
fmod(x, y) | 浮點數餘數 |
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double d = 200.374;
float f = 230.47f;
int i = -1000;
cout << "sin(d): " << sin(d) << endl;
cout << "abs(i): " << abs(i) << endl;
cout << "floor(d): " << floor(d) << endl;
cout << "sqrt(f): " << sqrt(f) << endl;
cout << "pow(d,2): " << pow(d, 2) << endl;
return 0;
}
輸出範例:
sin(d): -0.634939 abs(i): 1000 floor(d): 200 sqrt(f): 15.1812 pow(d,2): 40149.7
傳統 <cstdlib> 方案:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
srand(static_cast<unsigned>(time(nullptr))); // 種子
for (int i = 0; i < 10; ++i)
cout << "隨機數: " << rand() << endl;
return 0;
}
缺點: rand() 品質差、分布不均、執行緒不安全。
<random> (C++11)引擎 + 分布器分離設計,品質高、型別安全:
#include <iostream>
#include <random>
using namespace std;
int main() {
random_device rd; // 硬體熵源
mt19937 gen(rd()); // 梅森旋轉引擎
uniform_int_distribution<> dis(1, 100); // 均勻整數分布 [1,100]
for (int i = 0; i < 10; ++i)
cout << dis(gen) << ' ';
cout << endl;
normal_distribution<> nd(0.0, 1.0); // 常態分布 μ=0, σ=1
cout << "Normal: " << nd(gen) << endl;
return 0;
}
| 需求 | 建議型別 |
|---|---|
| 一般整數 | int (通常 32 位) |
| 大整數 / 位元操作 | long long / uint64_t |
| 一般浮點 | double (IEEE 754 雙精度) |
| 記憶體受限 / GPU | float / half |
| 金融 / 精確十進制 | 整數分單位或第三方十進制庫 |
<cmath>,注意弧度制與定義域錯誤。rand(),改用 <random> 引擎與分布器組合,獲得高品質、可重現、執行緒安全的隨機數。