需要帮助理解一个循环的单词
Need help understanding a word jumble for loop
此代码是杂乱无章的程序的一部分。我需要帮助了解for循环的工作方式并创建混乱的单词。例如,如果word ="苹果",输出将类似于:PLPEA。所以我想知道for循环中发生了什么以使此输出发生。
std::string jumble = theWord;
int length = theWord.size();
for (int i = 0; i < length; i++)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
std::cout << jumble << std::endl;
我将在for循环的每一行上添加注释:
for (int i = 0; i < length; i++) // basic for loop syntax. It will execute the same number of times as there are characters in the string
{
int index1 = (rand() % length); // get a random index that is 0 to the length of the string
int index2 = (rand() % length); // Does the same thing, gets a random index
char temp = jumble[index1]; // Gets the character at the random index
jumble[index1] = jumble[index2]; // set the value at the first index to the value at the second
jumble[index2] = temp; // set the value at the second index to the vaue of the first
// The last three lines switch two characters
}
您可以这样考虑:对于字符串中的每个字符,在字符串中切换两个字符。同样,%(或模量运算符)只是让剩余的了解模量运算符%
也必须了解mystring [index]将返回该索引的任何角色。例如:" Hello World" [1] ==" E"
相关文章:
- 使用一个循环与两个循环
- 如何通过一个循环将多个文件的内容分配给不同的类属性?
- 我对C++很陌生,我被困在试图做一个循环
- 该程序没有产生输出,而是卡在一个循环中,几秒钟后消失并打印被杀死?
- 有没有办法把它变成一个循环,让它更具包容性?
- 是否可以在一个循环中写入多个二进制文件
- C++在最后一个循环中排除了部分循环运算符
- 是否可以为一个循环设置多个条件
- 创建一个循环,该循环将输出大于零且小于 60(不包括 60)的所有 5 的倍数
- 如何创建一个循环,该循环检查每次迭代并在每次迭代后从头开始
- 如何在一个循环中分离两个不同的数组?
- 为什么这个do-while循环每隔一个循环只写入数组?
- 我在 c ++ 中有一个循环错误
- C :使用文件末端(CTRL Z)结束一个循环似乎打破了我程序的其余部分
- 如何将枯竭的健康转移到下一个循环中
- 一个循环,可以打印所有项目(无论链条多长时间) *指针
- 在 GtkDialog 中创建一个循环
- 我可以做一个循环,直到“std::cin”在输入缓冲区中看到“”字符
- 一个线程设置成员,而另一个循环上方 - 是此螺纹 - 不安全
- 编写一个循环,以检查变量的值与大量可能的有效值(C )的值