本範例示範如何使用 rand() 產生落在兩個不連續區間的隨機浮點數,並以系統時間為種子確保每次序列不同。
#include <cstdlib>
#include <ctime>
#include <iostream>
int main() {
// 以當前時間為種子
std::srand(static_cast<unsigned>(std::time(nullptr)));
// 產生 0.3000 ~ 0.6999 之間的值
double temp = static_cast<double>(std::rand() % 4000 + 3000) / 10000.0;
// 映射到目標區間:(0.1, 0.3) ∪ (0.7, 0.9)
temp = (temp < 0.5) ? (temp - 0.2) : (temp + 0.2);
std::cout << temp << std::endl;
return 0;
}
rand() % 4000 → 0~3999+ 3000 → 3000~6999/ 10000.0 → 0.3000~0.6999temp < 0.5 (0.3000~0.4999) → -0.2 → 0.1000~0.2999temp >= 0.5 (0.5000~0.6999) → +0.2 → 0.7000~0.8999#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0.0, 1.0);
double val = dis(gen);
double result = (val < 0.5)
? 0.1 + val * 0.4 // 0.1 ~ 0.3
: 0.7 + (val - 0.5) * 0.4; // 0.7 ~ 0.9
std::cout << result << std::endl;
}
優勢:均勻分佈更好、無模數偏差、執行緒安全、標準庫支援。