【问题标题】:How a for loop works without printingfor 循环如何在不打印的情况下工作
【发布时间】:2018-02-03 19:22:01
【问题描述】:

我看到有人发布了同样的 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();
}

【问题讨论】:

  • 使用打印会让你更清楚这种行为吗?
  • 如果两个索引相同,则不会发生变化。所以真的不需要检查。您是否运行调试器并逐步检查代码以尝试理解其步骤?
  • 好主意。我会看看它是否能让事情更清楚一点。仍然不确定我会理解为什么 rand() 不会从中复制字符
  • 所做的只是一个字符串中两个字符的交换。假设你有a=1b=2.. 你如何交换?您存储tmp=a 然后分配a=b 然后分配b=tmp - 现在a 是2 而b 是1。您的代码中唯一有点不同的是您交换数组中的字符,但仅此而已。
  • 它在每次迭代中交换两个字符(当然,除非 index1index2 发生两个相等)。迭代次数为lengthjumble.size()

标签: c++ arrays loops for-loop char


【解决方案1】:

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

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

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

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

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

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

字符是如何存储的?

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

如果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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多