C ++中数组中偶数和奇数索引元素的绝对差?
数组是具有相同数据类型的多个元素的容器。元素的索引从0开始,即第一个元素的索引为0。
在这个问题中,我们需要找到两个偶数索引号和两个奇数索引号之间的绝对差。
偶数编号=0、2、4、6、8…。
奇数索引编号=1,3,5,7,9...
绝对差是两个元素之间的差模量。
例如,
15和7的绝对差=(|15-7|)=8
Input: arr = {1 , 2, 4, 5, 8}
Output :
Absolute difference of even numbers = 4
Absolute difference of odd numbers = 3说明
偶数是1,4,8
绝对差是
(|4-1-)=3和(|8-4|)=4
奇数元素是2,5
绝对差是
(|5-2|)=3
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = { 1, 5, 8, 10, 15, 26 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The array is : \n";
for(int i = 0;i < n;i++){
cout<<" "<<arr[i];
int even = 0;
int odd = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0)
even = abs(even - arr[i]);
else
odd = abs(odd - arr[i]);
}
cout << "Even Index absolute difference : " << even;
cout << endl;
cout << "Odd Index absolute difference : " << odd;
return 0;
}
}输出结果
The array is : 1 5 8 10 15 26 Even index absolute difference : 8 Odd index absolute difference : 21