[英]How to select randomly the min element from a vector of integers in c++?
[英]how to select randomly from the entered inputs in c++?
我是 C++ 的新手,我正在制作一個程序,我們可以從輸入的名稱中隨機選擇 select。 當輸入的名字為10時,它只會隨機選擇一個名字,如果用戶從卷中輸入'Y',它會從之前輸入的名字中再次隨機選擇一個名字。
#include <iostream>
using namespace std;
int main()
{
string name;
int countname = 10;
char roll;
cout << "Please enter all the name of the entries: " << endl;
while (countname --) {
cin >> name;
}
do {
cout << "--------------------------" << endl;
cout << "Entries count: 10/10" << endl;
cout << "--------------------------" << endl;
cout << "THE WINNER IS: " << name << endl;
cout << "--------------------------" << endl;
cout << "CONGRATULATIONS TO YOU " << name << endl;
cout << "--------------------------" << endl;
cout << "Roll again? [Y]/[N]: ";
cin >> roll;
}
while (roll == 'Y');
return 0;
}
您需要存儲所有 10 個名稱。 您應該使用容器 - std::array或std::vector適合於此。 例如
std::string name;
std::vector<std::string> names;
while (countname --) {
cin >> name;
names.push_back(name);
}
對於隨機數,您可以使用這段代碼
#include <random>
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> rand(0,9);
std::cout << rand(rng) << std::endl;
並像這樣打印隨機名稱
const std::string winner = names[rand(rng)]
std::cout << winner << std::endl;
結果
Please enter all the name of the entries:
name_0
name_1
name_2
name_3
name_4
name_5
name_6
name_7
name_8
name_9
--------------------------
Entries count: 10/10
--------------------------
THE WINNER IS: name_3
--------------------------
CONGRATULATIONS TO YOU name_3
--------------------------
Roll again? [Y]/[N]: Y
--------------------------
Entries count: 10/10
--------------------------
THE WINNER IS: name_5
--------------------------
CONGRATULATIONS TO YOU name_5
--------------------------
Roll again? [Y]/[N]:
您只存儲姓氏,相反,您應該將所有名稱存儲在一個數組中。
要在數組中查找隨機名稱,請生成 0 到 9 之間的隨機索引(您可以使用rand() % 10
),該索引處的名稱將是隨機名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.