Presentation is loading. Please wait.

Presentation is loading. Please wait.

計算機程式語言實習課.

Similar presentations


Presentation on theme: "計算機程式語言實習課."— Presentation transcript:

1 計算機程式語言實習課

2 產生隨機亂數 產生隨機的亂數 亂數表 亂數種子 以時間當亂數種子

3 產生隨機亂數 引入標題檔 #include <stdlib.h> //亂數產生器
#include <time.h> //取得時間

4 產生隨機亂數 設定亂數種子 void srand(int seed); 取得亂數 回傳0~ 32767的值 int rand(void);
取得現在時間 int time(0);

5 產生隨機亂數 範例 每次執行都可以產生不同的亂數 #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; }

6 產生隨機亂數 如果不設定亂數種子 每次執行都是相同結果 #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; }

7 產生亂數 應用 數字遊戲 => 隨機出題 身分證字號產生器 產生樣品本作統計數字 隨機迷宮

8 產生隨機亂數 問題 如何產生10個隨機數字且不重複?

9 檔案讀寫 引入標題檔 #include <fstream> //讀寫IO 相當於螢幕輸出輸入的iostream

10 檔案讀寫 ifstream //讀取物件 ofstream //寫入物件 相當於cin與cout 但是用完必須關閉!!!

11 檔案讀寫 讀取範例 #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"); 宣告讀取物件 開啟檔案 讀取失敗? 取得資料 關閉讀取物件 螢幕輸出結果

12 檔案讀寫 寫入範例 #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"); } 宣告寫入物件 螢幕輸入資料 這是什麼? 開啟寫入目的 輸入資料 關閉寫入物件

13 檔案讀寫 檔案物件.open(“檔案名稱”,ios::開啟模式); ios::app 附加模式 末端增加資料 ios::ate
開啟資料 指標指向末端 ios::binary 二進位輸入輸出模式 ios::in 輸入模式 ios::out 輸出模式 ios::trunc 刪除已存資料 並開啟

14 檔案讀寫 輸入物件.eof() 判斷檔案是否結束 在ifstream中 判斷檔案是否結束 while(!in_stream.eof()) {
in_stream >> x; }


Download ppt "計算機程式語言實習課."

Similar presentations


Ads by Google