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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP