如果没有打印,for循环如何工作

问题描述 投票:0回答:1

我见过有人发布这个循环,但我的问题略有不同。变量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();
}
c++ arrays loops for-loop char
1个回答
1
投票

变量temp不会在每次迭代时被更改,所以只留下一个不断变化的字符吗?

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

但是因为在每次迭代中你都试图在位置charsjumbleindex1字符串的随机位置访问index2

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

每次迭代时,这些索引的值都是不可预测的。你可能会再次获得15

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

如何存储字符?

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

如果jumble = "Valentine"index1 = 1,那么你将访问a,因为你的V位于0位置。

另外,循环如何知道rand()不会为index1和index2生成相同的数字?

它没有。你必须提出一个策略来确保不会发生这种情况。一种方法,但不是一种有效方法,将是:

int index1 = (rand() % length);
int index2 = (rand() % length);
while (index1 == index2) {
    index1 = (rand() % length);
    index2 = (rand() % length);
}
© www.soinside.com 2019 - 2024. All rights reserved.