12个元素的数组 - 找到计数练习

时间:2017-12-06 00:35:43

标签: c++ arrays

请问你们能帮助我解决这个练习题吗? 我无法弄清楚答案是怎样的。

int arr[12] = { 1,3,5,0,7,2,0,4,4,0,8,8 };
int count = 0;
for (int i = 0; i<11; i++) {
    if (arr[i] = arr[i + 1])
        count++;
    else
        count--;
}
cout << count << endl;

1 个答案:

答案 0 :(得分:2)

在您的示例中,您有:

if (arr[i] = arr[i + 1])

=,而不是==。它指的是不检查相等性。所以在这个例子中:

if (a = 3) {

您将a分配给3并检查3是否为true。这样可以轻松查看为什么答案为5:

arr=>  { 1,3,5,0,7,2,0,4,4,0,8,8 };
count=>    1,2,1,2,3,2,3,4,3,4,5

如果您有兴趣,请在完成后查看数组。它看起来像这样:

{3,5,0,7,2,0,4,4,0,8,8,8} // Everything has been moved down 1 (except for the final member)

See a live example of this here