【发布时间】:2018-02-03 19:22:01
【问题描述】:
我看到有人发布了同样的 for 循环,但我的问题略有不同。变量temp 不会在每次迭代时都改变,所以只留下一个不断改变的字符?字符是如何存储的?此外,循环如何知道rand() 不会为index1 和index2 生成相同的数字?对不起,如果这不是很清楚,我有点新手!
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
enum { WORD, HINT, NUM_FIELDS };
const int NUM_WORDS = 3;
const std::string WORDS[NUM_WORDS][NUM_FIELDS] = {
{ "Redfield", "Main Resident Evil character" },
{ "Valentine", "Will you be mine?" },
{ "Jumbled", "These words are..." }
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
std::string theWord = WORDS[choice][WORD];
std::string theHint = WORDS[choice][HINT];
std::string jumble = theWord;
int length = jumble.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 << '\n'; // Why 'jumbled word' instead of just a character?
std::cin.get();
}
【问题讨论】:
-
使用打印会让你更清楚这种行为吗?
-
如果两个索引相同,则不会发生变化。所以真的不需要检查。您是否运行调试器并逐步检查代码以尝试理解其步骤?
-
好主意。我会看看它是否能让事情更清楚一点。仍然不确定我会理解为什么 rand() 不会从中复制字符
-
所做的只是一个字符串中两个字符的交换。假设你有
a=1和b=2.. 你如何交换?您存储tmp=a然后分配a=b然后分配b=tmp- 现在a是2 而b是1。您的代码中唯一有点不同的是您交换数组中的字符,但仅此而已。 -
它在每次迭代中交换两个字符(当然,除非
index1和index2发生两个相等)。迭代次数为length或jumble.size()。
标签: c++ arrays loops for-loop char