Re: [問題]大樂透電腦選號問題
看板C_and_CPP (C/C++)作者ericinttu (~ ~ ~)時間14年前 (2011/07/29 22:19)推噓1(1推 0噓 11→)留言12則, 4人參與討論串2/2 (看更多)
※ 引述《totoron10 (totoron)》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: 習題:請撰寫一程式來隨機產生6個號碼(1-49)
: ----------------------------------------
: 以下是程式碼:
: #include <stdio.h>
: #include <stdlib.h>
: #define randomize() srand((unsigned) time(NULL))
: #define random(x) (rand() % (x))
: int main
: {
: int loto[6],count=0,i;
: int flag;
: randomize();
: while(count<6){
: flag=0;
: loto[count]=random(49)+1;
: for(i=0;i<=count;i++)
: if(loto[count]==loto[i])
: flag=1;
: if(flag!=0)
: count++;
來小小推一下過程 :P
count: 0 (進去while)
flag : 0
loto[0] = 38 ((0~48)+1)
for(i=0;i<=0;i++) // count=0 時, i只會跑0. count=1 時, i會跑0跟1.
if(loto[0]==loto[i]) // 第count次的loto值 是否等於 第i次的loto值
flag: 1 // 是的話 flag 設為1 (是找到或是沒找到的意思?)
if(flag!=0) // 從這個 if 來看, flag 為1時, 應該是找到
count: 1 // 新的loto值, 所以 count要加1, 好讓下一輪
// 的亂數值可以放在正確的儲存格裡.
count < 6 (再進去while)
flag: 0
loto[1] = 38 (又這麼剛好跑到38)
for(i=0;i<=1;i++) i:0 i:1
if(loto[1]==loto[i]) Yes Yes
flag: 1 flag為1 flag為1
推到有點心虛...
反正, for-loop 裡的 i, 一定會跑到 i=count 的情況,
所以 for-loop 一定會遇到 loto[count] 等於 loto[i],
使得 flag 變成1.
所以, 不要說原PO不知道 flag 在做什麼. 我也不知道. XDDD
這個for-loop是寫好玩的嘛?
自己慢慢想流程, 慢慢拼出片段的程式, 還比啃下這個不知所云的程式碼好太多.
你遇到的問題, 我都遇過. 而且我還會問更白痴的問題呢!
別怕寫程式, 只要你腦袋裡的想法清楚了. 再配上適當的指令, 就可以寫出來了.
: }
: for(i=0;i<count;i++)
: printf("\n第%d 個樂透號碼:%d",i+1,loto[i]);
: printf("\n")
: system("PAUSE");
: return 0;
: }
: --------------------------------------------------------------------
: 1.想請問一下當中flag在程式中的用意是?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.117.183.236
→
07/29 22:21, , 1F
07/29 22:21, 1F
推
07/29 22:22, , 2F
07/29 22:22, 2F
→
07/29 22:23, , 3F
07/29 22:23, 3F
→
07/29 22:23, , 4F
07/29 22:23, 4F
→
07/29 22:27, , 5F
07/29 22:27, 5F
→
07/29 22:28, , 6F
07/29 22:28, 6F
→
07/29 22:29, , 7F
07/29 22:29, 7F
→
07/29 22:31, , 8F
07/29 22:31, 8F
→
07/29 22:46, , 9F
07/29 22:46, 9F
→
07/29 22:59, , 10F
07/29 22:59, 10F
→
07/29 23:11, , 11F
07/29 23:11, 11F
→
07/29 23:12, , 12F
07/29 23:12, 12F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章