c++ - 为什么我们在数东西的时候要加1?

标签 c++ function loops if-statement boolean

<分区>

我想知道,为什么我们使用 count++ 而不是例如 count += 0 来计算偶数的个数?

#include <iostream>
using namespace std;
int main()
{
    int count = 1;

    for (int i = 0; i <= 100; i++)
    {
        if (i % 2 == 0)
            count += 0;  // why it will give me only 1? as output
        else
            continue;
    }
    cout << "num of even: " << count << endl;

    system("pause");
    return 0;
}

最佳答案

count += 0; // why it will give me only 1? as output

count += 0 等同于 count = count + 0。您没有通过添加 0 添加任何内容。因此您的变量保持为 1。

why did we use count++ instead

count++ 不同于 count += 0。它以 1 递增 count,相当于 count += 1

至少,使用 count++,您“承认 i 是偶数”,因此对它进行计数。 (这背后是一个关于上下文和语言的完整领域,我宁愿不涉足。)

请注意,如果您要遍历大量项目,则添加 0 和 1 之间可能会有巨大差异。

关于c++ - 为什么我们在数东西的时候要加1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53363085/

相关文章:

c++ - C++中while(x--)是什么意思

c - 循环被忽略 - 指令仅执行一次

C++宏元编程

c++ - 从 "parent"项指针获取 `std::tuple` "children"

c++ - OpenGL 退化 GL_TRIANGLES 共享相同的顶点

function - 在 PostgreSQL 中截断模式中的所有表

我可以将 C 内联函数桥接到 Swift 吗?

c - 无限循环 : int vs. float

c++ - 带模板的 N 维嵌套元循环

javascript - JavaScript 中的变量作用域