用c++分别计算1-100的偶数和、奇数和
时间: 2024-09-20 07:15:57 浏览: 59
在C++中,我们可以使用循环结构来计算1到100之间的偶数和以及奇数和。这里提供两种常见的方式,一种是遍历数组,另一种是利用位操作。
1. 利用数组并初始化:
```cpp
#include <iostream>
int sumOfEvens(int limit) {
int sum = 0;
for (int i = 0; i <= limit; i += 2) { // 只取偶数
sum += i;
}
return sum;
}
int sumOfOdds(int limit) {
int sum = 0;
for (int i = 1; i <= limit; i += 2) { // 只取奇数
sum += i;
}
return sum;
}
int main() {
int totalEvens = sumOfEvens(100);
int totalOdds = sumOfOdds(100);
std::cout << "Sum of even numbers from 1 to 100: " << totalEvens << std::endl;
std::cout << "Sum of odd numbers from 1 to 100: " << totalOdds << std::endl;
return 0;
}
```
2. 利用位操作(仅适用于奇数和):
```cpp
#include <iostream>
int sumOfOdds(int n) {
if (n == 0) return 0;
n = n & -n; // 对于正整数,n & (-n) 会得到最小的奇数因子
int sum = 1;
while (n <= n + n) {
sum += n;
n <<= 1; // 将n翻倍
}
return sum;
}
int main() {
int totalEvens = 0; // 无法直接用位操作计算偶数和,需要常规循环
int totalOdds = sumOfOdds(100);
std::cout << "Sum of even numbers from 1 to 100: " << totalEvens << std::endl;
std::cout << "Sum of odd numbers from 1 to 100: " << totalOdds << std::endl;
return 0;
}
```
阅读全文