gpt4 book ai didi

c++ - 在二维数组 C++ 中打印一个字符串

转载 作者:行者123 更新时间:2023-12-01 13:56:01 25 4
gpt4 key购买 nike

我想问一下如何在二维数组中随机打印 Chessmaster 这个词的每个字母?我试过 srand 但我不知道如何将它与字符结合起来。有人可以帮我是代码。另外,我可以在没有 rand 的二维数组中创建随机字母吗?

#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX = 11;

using namespace std;

void printwo()
{
char word[MAX] = {'c', 'h', 'e', 's', 's', 'm', 'a', 's', 't', 'e', 'r'};
int c, i, n, letters;

cout << "I will print this word " << word << " sepereate" << endl;
srand(time(NULL));

for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[i] << "]"
<< "["
<< "]";
cout << endl;
}
}
}

int main()
{
int c;

cout << "Hello user press _1_ to continue" << endl;
cin >> c;

if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
exit(0);
}
return 0;
}

最佳答案

#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX = 11;

using namespace std;

// Generate a random number between min and max (inclusive)
// Assumes std::srand() has already been called
// Assumes max - min <= RAND_MAX
int getRandomNumber(int min, int max)
{
static constexpr double fraction { 1.0 / (RAND_MAX + 1.0) }; // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}

void printwo()
{
char word[MAX+1] = {"chessmaster"}; //If you are using C-style strings then you should declare +1 space
//int c, i, n, letters; not needed

cout << "I will print this word " << word << " sepereate" << endl;

//srand only gives a seed to yout tand function, you need to call std::rand() to get a random integer
//use the function getRandomNumber above that is based on rand() and gives you the possibility to select range
srand(time(NULL));

for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[getRandomNumber(0,10)] << "]"
<< "["
<< "]";
cout << endl;
}
}
}

int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;

if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
//exit(0); exit here not needed
}
return 0;
}

我写了一些评论.. 请阅读它们并问我是否有什么不明白的。我建议在这里阅读有关 C 风格字符串和 rand() 的内容: 兰德()-https://www.learncpp.com/cpp-tutorial/59-random-number-generation/ C 风格的字符串(基本上是 char 数组)- https://www.learncpp.com/cpp-tutorial/66-c-style-strings/

关于c++ - 在二维数组 C++ 中打印一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61049715/

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