gpt4 book ai didi

c++ - for循环如何在不打印的情况下工作

转载 作者:行者123 更新时间:2023-11-28 04:48:59 25 4
gpt4 key购买 nike

我看到有人发布了同样的 for 循环,但我的问题略有不同。变量 temp 不会在每次迭代中都发生变化,所以只留下一个不断变化的字符吗?字符是如何存储的?此外,循环如何知道 rand() 不会为 index1index2 生成相同的数字?抱歉,如果不是很清楚,我是个新手!

#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();
}

最佳答案

Wouldn't the variable temp be changed on each iteration, so just leaving one character that keeps getting changed?

这取决于。请注意,您试图在每次迭代中提出一个新的随机 index1 和一个新的随机 index2。如果您的 jumble 变量是 Redfield,并且 index1 = 1index2 = 5 会发生什么?您将交换两个 e

但是因为在每次迭代中,您都试图在 jumble 字符串的随机位置访问 chars 位置 index1index2:

int index1 = (rand() % length);
int index2 = (rand() % length);

这些索引的值在每次迭代中都是不可预测的。您可能会再次获得 15

不过,请记住,您在每次迭代中都创建了一个变量 temp,因此您不会更改它的值,您会在每次迭代中分配一个新变量。

How are the characters stored?

我不确定你在这里是什么意思,但每个字符都存储在 1 个字节内。因此,字符串将是一个字节序列 (char)。这个序列是一个连续的内存块。每次访问 jumble[index1] 时,您都在访问字符串 jumble 中位置 index1 上的字符。

如果 jumble = "Valentine"index1 = 1,那么您将访问一个 a,因为您的 V 在位置 0。

Also, how does the loop know that rand() won't generate the same number for both index1 and index2?

事实并非如此。你必须想出一个策略来确保这种情况不会发生。一种但不是有效的方法是:

int index1 = (rand() % length);
int index2 = (rand() % length);
while (index1 == index2) {
index1 = (rand() % length);
index2 = (rand() % length);
}

关于c++ - for循环如何在不打印的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601111/

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