题解 | #1-n之间偶数之和#
求 1 - n 之间偶数的和
http://www.nowcoder.com/practice/03df7fa0950046a9ba564b4438f918a3
//使用while循环
#include using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
//先获取1-n之间的所有偶数,然后再依次相加1.先判断是否是偶数,然后再相加
int i=0;
while(i<=n)
{
if(i%2==0)
{
sum+=i;
}
i++;
}
cout << sum << endl;
return 0;
} //do while循环 #include using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
int i=0;
do
{
if(i%2==0)
{
sum+=i;
}
i++;
}
while(i<=n);
cout << sum << endl;
return 0;
} //for 循环 #include using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
for(int i=0;i<=n;i++)
{
if(i%2==0)
{
sum+=i;
}
}
cout << sum << endl;
return 0;
}