史萊姆論壇

史萊姆論壇 (http://forum.slime.com.tw/)
-   程式語言討論區 (http://forum.slime.com.tw/f76.html)
-   -   C++問題 (http://forum.slime.com.tw/thread254688.html)

rainfire 2009-11-19 04:17 PM

C++問題
 
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
for(a=0;a<=7;a++)
{
b=rand()%42+1;
if(b<=42&&b>=0)
printf("%d\n",b);
}
system("pause");
return 0;
}

題目為:在1~42數字裡隨機挑出7個
但要每次都不同

這個程式跑出來結果每次都一樣
請問要如何解決
:on_47::on_47:

猜謎人 2009-11-20 09:52 AM

rand()
你的隨機種子是否都沒變啊

rand( (unsigned)time( NULL ) )可以嗎?

rainfire 2009-11-20 12:30 PM

引用:

作者: 猜謎人 (文章 2204635)
rand()
你的隨機種子是否都沒變啊

rand( (unsigned)time( NULL ) )可以嗎?

原來裡面可以這樣打@@
本來想打數字,他回報說不能給予條件,只能打void
我試看看,感謝幫忙

猜謎人 2009-11-21 04:29 PM

引用:

作者: rainfire (文章 2204647)
原來裡面可以這樣打@@
本來想打數字,他回報說不能給予條件,只能打void
我試看看,感謝幫忙

這樣管用嗎:on_47:

你的問題應該是隨機種子的問題

rainfire 2009-11-21 06:14 PM

引用:

作者: 猜謎人 (文章 2204811)
這樣管用嗎:on_47:

你的問題應該是隨機種子的問題

#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
for(a=0;a<=7;a++)
{
b=rand((unsigned)time(NULL))%42+1;
if(b<=42&&b>=0)
printf("%d\n",b);
}
system("pause");
return 0;
}

他編譯後說錯誤說:on_47:

pedrowong 2009-11-21 09:38 PM

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a,b;
srand( (unsigned)time( NULL ) );

for(a=0;a<=7;a++)
{
b=rand()%42+1;
if(b<=42&&b>=0)
printf("%d\n",b);
}
system("pause");
return 0;
}

rainfire 2009-11-22 01:08 AM

引用:

作者: pedrowong (文章 2204859)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a,b;
srand( (unsigned)time( NULL ) );

for(a=0;a<=7;a++)
{
b=rand()%42+1;
if(b<=42&&b>=0)
printf("%d\n",b);
}
system("pause");
return 0;
}

原來隨機種子要這樣打~~可是為什麼大大執行出來的答案有8個??

猜謎人 2009-11-22 09:39 AM

引用:

作者: rainfire (文章 2204889)
原來隨機種子要這樣打~~可是為什麼大大執行出來的答案有8個??

他的a從0起跳:on_66::on_66:

rainfire 2009-11-22 10:10 AM

引用:

作者: 猜謎人 (文章 2204909)
他的a從0起跳:on_66::on_66:

所以如果是要取7位
應當a=1是嗎?

pedrowong 2009-11-22 09:17 PM

引用:

作者: rainfire (文章 2204889)
原來隨機種子要這樣打~~可是為什麼大大執行出來的答案有8個??

for(a=0;a<=7;a++)
{
b=rand()%42+1;
if(b<=42&&b>=0)
printf("%d\n",b);
}

以上程式跑了八次,不是嗎?(你寫的,你忘了?)
for(a=0;a<=7;a++) 改為 for(a=0;a<7;a++)
就會執行七次。

rainfire 2009-11-23 01:27 AM

引用:

作者: pedrowong (文章 2204993)
for(a=0;a<=7;a++)
{
b=rand()%42+1;
if(b<=42&&b>=0)
printf("%d\n",b);
}

以上程式跑了八次,不是嗎?(你寫的,你忘了?)
for(a=0;a<=7;a++) 改為 for(a=0;a<7;a++)
就會執行七次。

不知道耶==
第一次寫時跑出7個
後來看完你得再跑變8個!!
:on_47::on_47::on_51::on_51:


所有時間均為台北時間。現在的時間是 09:25 AM

Powered by vBulletin® 版本 3.6.8
版權所有 ©2000 - 2025, Jelsoft Enterprises Ltd.

『服務條款』

* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *


SEO by vBSEO 3.6.1