gpt4 book ai didi

c++ - 如何在 C++ 中创建单词/句子输出的随机机会

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:19 25 4
gpt4 key购买 nike

我只是想知道我怎么能做到这一点。这是我想要的代码片段:

/**< CASPOR's question script */
if (input == "N")
{
cout << "Ok, " << name << " would you like to ask me a simple question?\n";
cin >> input;
{
if (input == "Y")
{
while ("Y")
{
cout << "Ask away!\n";
cin.ignore();
getline(cin, input);
{
if (input == "Who are you?")
{
cout << "I am CASPOR, or a C++ Automated Speech Program Of Recognition.\n";
}

if (input == "What is your purpose?")
{
cout << "My purpose is to entertain and amaze. Almost like a boredom breaker.\n";
}

if (input == "What can you do?")
{
cout << "I can do anything the developers program me to do!";
}
cout << "Would you like to ask another question?\n";
cin >> input;
{
if (input == "Y")
continue;
}
}
}
}
}
}

“CASPOR” 回答您问题的地方,我怎样才能包含他每次都会说不同话的机会?

最佳答案

您可以将答案存储在容器中(通常是 std::vector<std::string>> )并使用 std::shuffle 随机化它。

然后只需选择 vector 中的第一个答案。

示例:

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <random>
#include <chrono>

int main()
{
// Initialize the seed
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// Store the answers
std::vector<std::string> answers = { "Answer1" , "Answer2", "Answer3", "Answer4" };

for(std::size_t n = 0 ; n <10 ; ++n)
{
// Randomize the vector
std::shuffle(std::begin(answers), std::end(answers), std::default_random_engine(seed));
std::cout << answers[0] << '\n';
}
}

Live demo

注意事项:

  • 你的 if应该是 if ... else if ... else if ...
  • 你的 while ("Y")毫无意义,就做while(true)

关于c++ - 如何在 C++ 中创建单词/句子输出的随机机会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25437248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com