我们给了两个整数类型的元素数组,分别是arr_1 []和arr_2 [],任务是从arr_1 []中选择一个元素,并从arr_ []中选择另一个元素以形成一对,然后计算配对并检查结果总和是否为偶数。
输入值
int arr_1[] = {2, 3, 7, 1, 4} int arr_2[] = { 2, 4, 1, 3}
输出结果
Count Pairs from two arrays with even sum are: 10
说明
We will form the pairs using both the arrays and the pairs so formed are-: (2, 2) = 4(valid), (2, 4) = 6(valid), (2, 1) = 3(invalid), (2, 3) = 5(invalid), (3, 2) = 5(invalid), (3, 4) = 7(invalid), (3, 1) = 4(valid), (3, 3) = 5(valid), (7, 2) = 9(invalid), (7, 4) = 11(invalid), (7, 1) = 8(valid), (7, 3) = 10(valid), (1, 2) = 3(invalid), (1, 4) = 5(invalid), (1, 1) = 2(valid), (1, 3) = 4(valid), (4, 2) = 6(valid), (4, 4) = 8(valid), (4, 1) = 5(invalid), (4, 3) = 7(invalid). There are 10 valid pairs formed using given two arrays that are even sums.
输入值
int arr_1[] = {3, 1, 2} int arr_2[] = { 2, 4}
输出结果
Count Pairs from two arrays with even sum are: 2
说明
We will form the pairs using both the arrays and the pairs so formed are-: (3, 2) = 5(invalid), (3, 4) = 7(invalid), (1, 2) = 3(invalid), (1, 4) = 5(invalid), (2, 2) = 4(valid), (2, 4) = 6(valid), . There are 2 valid pairs formed using given two arrays that are even sums.
输入两个整数类型元素的数组,并计算两个数组的大小,然后将数据传递给函数以进行进一步处理。
以一个临时变量作为计数来存储偶数和的对数
从i到0开始循环FOR直到数组1的大小
在循环内部,从j到0直到数组2的大小开始另一个循环FOR。
现在将arr_1 [i]和arr_2 [j]之和存储在一个整数变量中,假设总和
检查IF总和%2 == 0,即总和是否为偶数。如果是,则将计数加1。
返回计数
打印结果。
#include <iostream> using namespace std; int even_pair(int arr_1[], int size_arr1, int arr_2[], int size_arr2){ int count = 0; int odd = 0; for(int i = 0 ;i <size_arr1 ; i++){ for(int j = 0; j<size_arr2 ; j++){ int even = arr_1[i] + arr_2[j]; if(even % 2 == 0){ count++; } } } return count; } int main(){ int arr_1[] = {2, 3, 7, 1, 4}; int arr_2[] = { 2, 4, 1, 3}; int size_arr1 = sizeof(arr_1) / sizeof(arr_1[0]); int size_arr2 = sizeof(arr_2) / sizeof(arr_2[0]); cout<<"Count Pairs from two arrays with even sum are: "<<even_pair(arr_1, size_arr1, arr_2, size_arr2); return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count Pairs from two arrays with even sum are: 10