在 for 循环中使用模数

dmu*_*ubu 2 c for-loop modulo

我试图了解如何使用 mod 运算符重复循环。

如果有两个字符串"abc""defgh",如何%用于循环,重复直到到达abc结尾?defghabc和的长度的模关系是什么defgh

我不太明白这个概念。

dec*_*iar 5

简单的。

std::string abc("abc");
std::string defgh("defgh");

for (size_t i = 0; i < defgh.length(); ++i)
{
    printf("%c", abc[i % abc.length()]);
}
Run Code Online (Sandbox Code Playgroud)

想想模运算符正在做什么,它离散地将左侧除以右侧,然后吐回整数余数。

例子:

0 % 3 == 0
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0
4 % 3 == 1
Run Code Online (Sandbox Code Playgroud)

在我们的例子中,左边代表“defgh”中的第i个位置,右边代表“abc”的长度,结果是“abc”内的循环索引。

  • 好像概念无论如何都改变了;他不妨弄清楚如何将其转换为 C... (5认同)