Sar*_*_Xx 1 c++ loops if-statement boolean function
我想知道,为什么我们使用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;
}
Run Code Online (Sandbox Code Playgroud)
Tre*_*edJ 10
count + = 0; //为什么它会给我一个?作为输出
count += 0相当于count = count + 0.您不是通过添加0来添加任何内容.因此您的变量保持为1.
为什么我们使用count ++代替
count++不同于count += 0.它增加count由1和相当于count += 1.
至少,有count++,你是"承认这i是一个偶数"并因此计算它.(在这背后是关于背景和语言的整个土地,我宁愿不进入.)
请注意,如果要迭代大量项目,则添加0和1之间可能存在巨大差异.