我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?

I have an array and I want to input a range , and then find the sum of all even numbers in the range?

本文关键字:范围内 范围 输入 数组 有一个 一个 然后      更新时间:2023-10-16

数组在代码中给出,我的输入是两个数字,就像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;
}