在数组C++中,如何使用输入用户获取奇数和偶数的和

  • 本文关键字:获取 用户 C++ 数组 何使用 c++
  • 更新时间 :
  • 英文 :


我们的编程活动是构建一个C程序,创建一个大小为12的数组,然后分别显示偶数索引单元格和奇数索引单元格的总和及其平均值。示例运行必须是这样的。

示例运行:输入12个元素:1 1 11 1 1 1 1 11 11 1 1

偶数索引单元格的总和:6

奇数索引单元格之和:6

平均:6.0

然而,我在求奇数和偶数的和时遇到了麻烦。比如我如何让程序识别数组中的奇数和偶数位置?我需要添加";如果其他";这是我的密码。

#include <iostream>
using namespace std;
int A[11],B[11],C[11];
int sum,ave;
int x;
main()
{
cout<<"Enter 12 elements A: "<<endl;
for(x=0; x<11; x++) 
cin>>A[x];
cout<<endl<<"Sum of even-indexed number: "<<endl;
for(x=0; x<=11; x++){
cout<<B[x];
}           
cout<<endl<<"Sum of odd-indexed number: "<<endl;
for(x=0; x<=11; x++){
cout<<C[x];
}

cout<<endl<<"Average: "<<endl;
for(x=3; x<3; x++)
ave += B[x]+C[x]/A[x];
cout<<A[x]<<" ";
return 0;
}

您不需要3个数组。元素只有一个数组,偶数和赔率的总和只有两个变量。

您可以通过检查索引的余数除以2是否等于0来检查数组中的位置。

你也可以开始一个偶数位置,并将索引增加2,这样它只会检查偶数位置。对于奇数位置,执行相同操作,增量为2,但从奇数位置开始。

#include <iostream>
using namespace std;
int main() {
int array[12];
int evenTotal = 0;
int oddTotal = 0;
for(int i=0;i<12;i++) {
cin>>array[i];
cout<<array[i]<<" ";
if(i%2 == 0){
//If we consider indexing with 0 to 11
// If we consider indexing with 1 to 12
// than this condition will be odd
evenTotal += array[i];
}
else {
oddTotal += array[i];
}
}
cout<<"n";
// Because we have 6 evens and odds
int average = (evenTotal + oddTotal)/12;
cout<<"Even Total = "<<evenTotal<<"n";
cout<<"Ödd Total = "<<oddTotal<<"n";
cout<<"Average = "<<average;
return 0;
}

在此处检查输出:https://ideone.com/msYFh5

最新更新