產生隨機亂數 - HiNet

Download Report

Transcript 產生隨機亂數 - HiNet

計算機程式語言實習課
產生隨機亂數




產生隨機的亂數
亂數表
亂數種子
以時間當亂數種子
產生隨機亂數
 引入標題檔
#include <stdlib.h>
#include <time.h>
//亂數產生器
//取得時間
產生隨機亂數
 設定亂數種子
void srand(int seed);
 取得亂數 回傳0~ 32767的值
int rand(void);
 取得現在時間
int time(0);
產生隨機亂數
 範例 每次執行都可以產生不同的亂數
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(0));
for (int i=0;i<10;i++)
cout << rand() << endl;
system("pause");
return 0;
}
產生隨機亂數
 如果不設定亂數種子 每次執行都是相同結果
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(101);
for (int i=0;i<10;i++)
cout << rand() << endl;
system("pause");
return 0;
}
產生亂數
 應用





數字遊戲
=>
身分證字號產生器
產生樣品本作統計數字
隨機迷宮
…
隨機出題
產生隨機亂數
 問題
如何產生10個隨機數字且不重複?
檔案讀寫
 引入標題檔
#include <fstream>
//讀寫IO
 相當於螢幕輸出輸入的iostream
檔案讀寫
 ifstream
 ofstream
//讀取物件
//寫入物件
 相當於cin與cout
 但是用完必須關閉!!!
檔案讀寫
 讀取範例
#include <fstream>
#include <iostream>
using namespace std;
宣告讀取物件
開啟檔案
void main()
{
ifstream in_stream;
int f,s,t;
in_stream.open("D:\\程式設計\\C++\\Debug\\123.txt");
if (in_stream.fail())
{
cout << "開啟檔案失敗!\n";
讀取失敗?
取得資料
exit(1);
}
in_stream >> f >> s >> t; cout << f << s << t;
in_stream.close();
system("pause");
關閉讀取物件
螢幕輸出結果
}
檔案讀寫
 寫入範例
#include <fstream>
宣告寫入物件
#include <iostream>
using namespace std;
void main()
{
ofstream out_stream;
int f,s,t;
cin >> f >> s >> t;
}
螢幕輸入資料
這是什麼?開啟寫入目的
out_stream.open("D:\\程式設計\\C++\\Debug\\123.txt",ios::app);
out_stream << f << “ “ << s << “ “<< t << “ “ ;
out_stream.close();
system("pause");
輸入資料
關閉寫入物件
檔案讀寫
檔案物件.open(“檔案名稱”,ios::開啟模式);
ios::app
ios::ate
ios::binary
ios::in
ios::out
ios::trunc
附加模式 末端增加資料
開啟資料 指標指向末端
二進位輸入輸出模式
輸入模式
輸出模式
刪除已存資料 並開啟
檔案讀寫
 輸入物件.eof()
 判斷檔案是否結束
 在ifstream中 判斷檔案是否結束
while(!in_stream.eof())
{
in_stream >> x;
…
}