程式功能
- 生成 20 個 4 位隨機整數 (1000-9999)。
- 篩選「個位與十位相同」的數字(如 12**33**、56**77**)。
- 結果輸出到控制台並寫入
randnumber.txt。
完整代碼(現代化修正版)
#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <vector>
int main() {
// 1. 種子初始化(僅一次)
std::srand(static_cast<unsigned>(std::time(nullptr)));
// 2. 生成 20 個 4 位隨機數
std::vector<int> nums;
nums.reserve(20);
std::cout << "生成的隨機數:\n";
while (nums.size() < 20) {
int v = std::rand() % 9000 + 1000; // 1000-9999
nums.push_back(v);
std::cout << v << (nums.size() % 5 == 0 ? '\n' : '\t');
}
// 3. 篩選:個位 == 十位
std::ofstream ofs("randnumber.txt");
std::cout << "\n個位與十位相同的數:\n";
for (int v : nums) {
int ones = v % 10;
int tens = (v / 10) % 10;
if (ones == tens) {
std::cout << v << ' ';
ofs << v << ' ';
}
}
ofs.close();
std::cout << "\n結果已寫入 randnumber.txt\n";
return 0;
}
關鍵點解析
| 原代碼問題 | 修正說明 |
void main() | 標準 C++ 必須 int main()。 |
全域陣列 t[300] + 1-based 索引 | 改用 std::vector 0-based,邊界安全。 |
DeleteFile / system("pause") | 移除平台相關調用,提高可移植性。 |
rand() 質量差、線程不安全 | 教學可接受;生產環境請用 <random> (C++11)。 |
現代 C++11 <random> 寫法(推薦)
#include <random>
#include <vector>
#include <fstream>
#include <iostream>
int main() {
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(1000, 9999);
std::vector<int> nums(20);
for (int& v : nums) v = dist(rng);
std::ofstream ofs("randnumber.txt");
for (int v : nums) {
if ((v % 10) == ((v / 10) % 10)) {
std::cout << v << ' ';
ofs << v << ' ';
}
}
}
mt19937:梅森旋轉算法,週期 2^19937-1,統計特性優秀。
uniform_int_distribution:無模運算偏差,均勻分佈。
random_device:硬體熵源種子(若不可用退回偽隨機)。