数组(C ++)中偶数和奇数索引元素的绝对差?
在这里,我们将看到如何获取数组中奇数和偶数索引元素的绝对差。绝对差表示如果一对差为负,则取绝对值。例如,让数字为{1、2、3、4、5、6、7、8、9}。因此,偶数位置元素为1、3、5、7、9(从0开始),奇数位置元素为2、4、6、8。因此,偶数位置数据的差为| 1-3 |。= 2,然后| 2-5 | = 3,| 3-7 | = 4和| 4-9 | = 5同样,位数的奇数差将为4。
算法
offEvenDiff(arr,n)
begineven := 0
odd := 0
for i := 0 to n-1, do
if i is even, then
even := |even – arr[i]|
else
odd := |odd – arr[i]|
done
return (odd,even)
end
示例
#include<iostream>#include<cmath>
using namespace std;
void oddEvenDiff(int arr[], int n, int &o, int &e) {
int even = 0;
int odd = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
even = abs(even - arr[i]); //get the even difference
} else {
odd = abs(odd - arr[i]);
}
}
e = even;
o = odd;
}
main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int odd, even;
oddEvenDiff(arr, n, odd, even);
cout << "The odd and even differences are: " << odd << " and " << even;
}
输出结果
The odd and even differences are: 4 and 5
以上是 数组(C ++)中偶数和奇数索引元素的绝对差? 的全部内容, 来源链接: utcz.com/z/343499.html