数组在代码中给出,我的输入是两个数字,例如
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;
}
答案 0 :(得分:0)
由于要对开始和结束之间的数字求和,因此需要更改循环以使用输入的值。更改为此:
gcloud beta firestore export gs://myapp-backup-dev --collection-ids='testStuff'
gcloud beta firestore import gs://myapp-backup-dev/2018-10-15T21:38:18_36964 --collection-ids='testStuff'
此外,删除根本不需要的行for(int i = n1; i <= n2; i++){
if(a[i] % 2 == 0){
S = S + a[i];
found = 1;
}
}
。
答案 1 :(得分:0)
尝试一下:
#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;
}