简体   繁体   English

我不明白 C++ 中的 ++ 运算符

[英]I don't understand ++ operators in c++

在此处输入图片说明

when I compile this, I get当我编译这个时,我得到

j is: 28  k is: 50
V H 

What I do not understand is, why is the j++ and k++ 28 and 50 and not 27 and 48, respectively?我不明白的是,为什么j++k++ 28 和 50 而不是 27 和 48? I don't understand why it adds 3+, and not 1+.我不明白为什么它增加了 3+,而不是 1+。

The condition (txt[j] == txt[k]) is true for 3 values, '-', 'I', and '-'.条件(txt[j] == txt[k])对于 3 个值“-”、“I”和“-”为真。 So you add three to 25, and add 3 to 47. The before/after increment is only different on the line it happens.所以你在 25 上加 3,在 47 上加 3。之前/之后的增量只是在它发生的那一行上不同。

If you had:如果你有:

int x = 10;
int y = 10;
cout << x++;
cout << ++y;

you would see that x's value would be 10 at the time it was printed, and y's value would be 11.您会看到 x 的值在打印时为 10,而 y 的值为 11。

if you then just printed them again without changing them a second time they should both be 11.如果您然后再次打印它们而没有第二次更改它们,它们都应该是 11。

=========================== ============================

With your values it works like this:使用您的值,它的工作方式如下:

Txt [25] is letter '-' in the string. Txt [25] 是字符串中的字母“-”。 It's like the 4th '-' in. Text[47] is also the letter '-', it's like the 8th '-' in the string.就像第 4 个“-”。Text[47] 也是字母“-”,就像字符串中的第 8 个“-”。 The condition of the loop says to continue running the increment opperators on these two indexes while they are the same value.循环的条件是继续在这两个索引上运行增量运算符,同时它们的值相同。 So they are the same, both get incremented.所以它们是相同的,两者都会增加。 Now we look at letters 26, and 48. These are both 'I', which is the same again.现在我们看看字母 26 和 48。它们都是“I”,这又是一样的。 So we increment a third time, 27, and 49 Are both '-' again, so we increment again.所以我们第三次递增,27和49都是'-',所以我们再次递增。 Now 28 is at 'V' (the start of 'VAAR'), and 50 is at 'H' the start of 'HOST'.现在 28 位于“V”(“VAAR”的开头),而 50 位于“H”,即“HOST”的开头。 'H' is not equal to 'V' so we stop looping here. 'H' 不等于 'V' 所以我们在这里停止循环。

You're starting your compare at "-IV" and "-IH" .您从"-IV""-IH"开始比较。 So there are three characters that match.所以有三个匹配的字符。

Preincrement ++k and postincrement j++ both increment the variables. Preincrement ++k和 postincrement j++都增加变量。 The difference in how they behave as right hand side arguments, eg int z = ++k;它们作为右侧参数的行为方式的不同,例如int z = ++k; vs int z = k++; vs int z = k++; . . The former increments k and assigns its new value to z .前者增加k并将其新值分配给z The latter assigns the current value of k to z and then increments k ;后者将k的当前值赋给z然后递增k

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM