简体   繁体   English

c ++中的代码是什么意思?

[英]What does the code in c++ mean?

I do not understand what is going on on variable k. 我不明白变量k上发生了什么。 For example I tried to put 1, 2, 3, 4, 5 but k shows me 1. 例如,我试图把1,2,3,4,5,但k显示我1。

    int a[5];
    for (int i = 0; i < 5; i++) {
        cin >> a[i];
    }

    int k = 0;
    for(int j = 0; j < 5; j++) {
        k += a[j] > a[j+1];
    }
    cout << k;

k shows a value of one because you are accessing out of bounds array a. k显示值为1,因为您正在访问超出范围的数组a。

When j = 4 , j+1 is 5 and so you are trying to access a[5] which is out of bound. j = 4j+15 ,因此您试图访问超出范围a[5] Hence it is incorrectly showing that a[j] > a[j+1] for one value. 因此,它错误地显示a[j] > a[j+1] This is undefined behaviour. 这是未定义的行为。

Change your code to: 将您的代码更改为:

for(int j = 0; j < 4; j++) {
  k += a[j] > a[j+1];
}

Now k will have a value of 0 if the input series is 1, 2, 3, 4 and 5. 如果输入序列为1,2,3,4和5,则k的值为0。

a[j] > a[j+1] produces a Boolean result ( false or true ). a[j] > a[j+1]产生布尔结果( falsetrue )。 In an int context, true and false convert to 1 and 0 respectively. int上下文中, truefalse分别转换为10

So, this is roughly equivalent to: 所以,这大致相当于:

for (int j=0; j<5; j++)
    if (a[j] > a[j+1])
        ++k;

The loop iterates over the array a , comparing a[0] > a[1] , a[1] > a[2] , a[2] > a[3] etc.. When a boolean is added to an integer, it's first converted to 0 (if false) or 1 (if true). 循环遍历数组a ,比较a[0] > a[1]a[1] > a[2]a[2] > a[3]等。当布尔值添加到整数时,它首先转换为0(如果为假)或1(如果为真)。 So, k ends up being a count of the number of times an element if greater than the following element. 因此, k最终是元素的次数,如果大于以下元素。

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

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