我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
I have an array and I want to input a range , and then find the sum of all even numbers in the range?
数组在代码中给出,我的输入是两个数字,就像
2, 7
和数组的第二和第七元素之间代码需要找到所有偶数的总和。我该怎么做?
#include <iostream>
using namespace std;
int main(){
int S, n1, n2;
cont int n = 8;
int found = 0;
cout << "Enter the beginning of a range: ";
cin >> n1;
cout << "Enter the end of a range: ";
cin >> n2;
int a[] = {1, 5, 9, 6, 2, 7, 4, 3};
int i;
for(i = 0;i <= n; i++){
if(a[i] % 2 == 0){
S = S + a[i];
found = 1;
}
}
if(found == 1){
cout << "Even numbers found" << " " << "Sum: " << S <<endl;
}
else{
cout << "Even numbers not found" <<endl;
}
return 0;
}
由于您要对开始和结束之间的数字求和,因此您需要更改循环以使用您输入的值。将其更改为:
for(int i = n1; i <= n2; i++){
if(a[i] % 2 == 0){
S = S + a[i];
found = 1;
}
}
另外,删除根本不需要的行cont int n = 8;
。
试试这个:
#include <iostream>
using namespace std;
int main()
{
int S, n1, n2;
cont int n = 8;
int found = 0;
cout << "Enter the beginning of a range: ";
cin >> n1;
cout << "Enter the end of a range: ";
cin >> n2;
int a[] = { 1, 5, 9, 6, 2, 7, 4, 3 };
int i;
for (; n1 <= n2; n1++)
{
if (a[n1] % 2 == 0)
{
S = S + a[n1];
found = 1;
}
}
if (found == 1)
{
cout << "Even numbers found" << " " << "Sum: " << S << endl;
}
else
{
cout << "Even numbers not found" << endl;
}
return 0;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 并行用于C++17中数组索引范围内的循环
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 不计算一个范围内的完美数
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 未在此范围内声明错误 'xy'
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 命名空间范围内的外部 - GCC vs clang vs msvc
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 如何仅使用 While 循环在给定范围内找到可被 7 整除的计数整数
- Socklen_t未在此范围内声明
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- 查找给定范围内最长连续 1 的频率
- "Main"已在当前范围内声明
- c++ 变量在宏的扩展中没有在这个范围内声明
- 变量不在 lambda 的范围内