首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 數值型別與數學運算完全指南:基本型別、cmath 函式庫、隨機數生成

     編輯:C++ 入門

C++ 數值型別與數學運算完全指南

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() 品質差、分布不均、執行緒不安全。

現代 C++ 隨機數 <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 雙精度)
記憶體受限 / GPUfloat / half
金融 / 精確十進制整數分單位或第三方十進制庫

總結

  • 理解基本型別範圍與精度,避免溢位與精度損失。
  • 數學運算包含 <cmath>,注意弧度制與定義域錯誤。
  • 棄用 rand(),改用 <random> 引擎與分布器組合,獲得高品質、可重現、執行緒安全的隨機數。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved