DoModal() 呼叫後阻塞父視窗,使用者必須關閉才能繼續操作(如開啟檔案對話框)。Create() 建立,不阻塞父視窗,可同時操作(如尋找/取代對話框)。CDialog 派生類 → 加入變數/驗證/訊息映射 → OnInitDialog 初始化 → DoModal() 顯示。北京體育彩票 36 選 7:隨機產生 7 個 1~36 不重複號碼,按大小排序,顯示於 7 個編輯框。
srand((unsigned)time(NULL)); // 以當前時間為種子,確保每次序列不同
原理:rand() 產生偽隨機序列,種子相同則序列相同。time(NULL) 秒級變化保證種子差異。
int num = rand() % 36 + 1; // 餘數 0~35 + 1 → 1~36
BOOL IsDuplicate(int num, int* arr, int count)
{
for (int i = 0; i < count; i++)
if (arr[i] == num) return TRUE;
return FALSE;
}
void SortNumbers(int* arr, int count)
{
for (int i = 0; i < count - 1; i++)
for (int j = 0; j < count - 1 - i; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
CGuessDlg,加入 7 個 CString 變數 m_strNum1...m_strNum7 (DDX_Text)。BN_CLICKED → OnBtnPick()。void CGuessDlg::OnBtnPick()
{
int numbers[7] = {0};
int count = 0;
srand((unsigned)time(NULL));
while (count < 7)
{
int num = rand() % 36 + 1;
if (!IsDuplicate(num, numbers, count))
{
numbers[count++] = num;
}
}
SortNumbers(numbers, 7);
// 指派給 CString 變數,UpdateData(FALSE) 刷新介面
m_strNum1.Format(_T("%d"), numbers[0]);
m_strNum2.Format(_T("%d"), numbers[1]);
m_strNum3.Format(_T("%d"), numbers[2]);
m_strNum4.Format(_T("%d"), numbers[3]);
m_strNum5.Format(_T("%d"), numbers[4]);
m_strNum6.Format(_T("%d"), numbers[5]);
m_strNum7.Format(_T("%d"), numbers[6]);
UpdateData(FALSE);
}
| 知識點 | 說明 |
|---|---|
| 模態對話框建立流程 | 資源 → ClassWizard → 變數/訊息 → DoModal |
| 隨機數種子 | srand(time(NULL)) 確保非固定序列 |
| 範圍映射 | rand() % N + min → [min, max] |
| 去重演算法 | 線性搜尋,資料量小(7)效能足夠 |
| 排序演算法 | 氣泡排序,簡單易懂,N=7 極快 |
| DDX 機制 | CString 變數雙向綁定編輯框 |