算法思路:使用隨機函數來模擬自然界中發生的不可預測情況。(srand() 和 rand()函數生成隨機數)
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int count=0;
int num = rand()%100 + 1;
int guess;
cout << "請輸入猜測的數值:";
cin >> guess;
do{
if (guess > num){
count++;
cout << "您猜的值大了\n";
cout << "請再次輸入猜測的數值:";
cin >> guess;
}else if (guess < num){
count++;
cout << "您猜的值小了\n";
cout << "請再次輸入猜測的數值:";
cin >> guess;
}
}while(guess != num);
count++;
cout << "猜中了!\n";
cout << "共猜了 " << count << " 次\n";
return 0;
}
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
void play(int n);
void play(int n)
{
int i,m=0,t=0;
for(i=0; i<n; i++)
{
t=rand()%6+1;
m+=t;
cout << "第" << (i+1) << "粒骰子的點數爲:" << t <<"\n";
}
cout << "總共" << m << "點\n";
}
int main()
{
int people,numbers;
do{
srand(time(NULL));
cout << "請輸入參與的人數:";
cin >> people;
if(people == 0) break;
cout << "請輸入骰子的數量:";
cin >> numbers;
if(numbers == 0) break;
for(int i=0; i<people; i++)
{
cout << "第 " << (i+1) << "位選手擲出的骰子情況爲:\n";
play(numbers);
}
}while(1);
return 0;
}
C++產生隨機數的用法
1) 給srand()提供一個種子,它是一個unsigned int類型;
2) 調用rand(),它會根據提供給srand()的種子值返回一個隨機數(在0到RAND_MAX之間);
3) 根據需要多次調用rand(),從而不間斷地得到新的隨機數;
4) 無論什麼時候,都可以給srand()提供一個新的種子,從而進一步“隨機化”rand()的輸出結果。
產生一定範圍隨機數的通用表示公式
要取得[a,b)的隨機整數,使用(rand() % (b-a))+ a;
要取得[a,b]的隨機整數,使用(rand() % (b-a+1))+ a;
要取得(a,b]的隨機整數,使用(rand() % (b-a))+ a + 1;
通用公式:a + rand() % n;其中的a是起始值,n是整數的範圍。