给定一个n个整数的数组arr [n],任务是找到所有成对连续元素的乘积。
数组arr []中的连续元素是,如果我们位于第ith个元素,即arr [i],则其连续元素将是arr [i + 1]或arr [i-1],因此乘积将是arr [ i] * arr [i + 1]或arr [i] * arr [i-1]。
输入值
arr[] = {1, 2, 3, 4}
输出结果
2, 6, 12
说明
Splitting into pairs {1,2}, {2, 3}, {3, 4} Their results will be 1*2 = 2, 2*3 = 6, 3*4 = 12
输入值
arr[] = {9, 5, 1, 2, 6, 10}
输出结果
45, 5, 2, 12, 60
说明
Splitting into pairs {9, 5}, {5, 1}, {1, 2}, {2, 6}, {6, 10} Their results will be 9*5 = 45, 5*1 = 5, 1*2 = 2, 2*6=12, 6*10=60
从数组的第0个元素开始循环,直到小于n-1。
对于每个我检查其i + 1的产品,每个i和i + 1的产品都会打印结果。
Start Step 1→ Declare function to calculate product of consecutive elements void product(int arr[], int size) Declare int product = 1 Loop For int i = 0 and i < size – 1 and i++ Set product = arr[i] * arr[i + 1] Print product End Step 2 → In main() Declare int arr[] = {2, 4, 6, 8, 10, 12, 14 } Declare int size = sizeof(arr) / sizeof(arr[0]) Call product(arr, size) Stop
#include <iostream> using namespace std; //函数查找连续对的乘积 void product(int arr[], int size){ int product = 1; for (int i = 0; i < size - 1; i++){ product = arr[i] * arr[i + 1]; printf("%d ", product); } } int main(){ int arr[] = {2, 4, 6, 8, 10, 12, 14 }; int size = sizeof(arr) / sizeof(arr[0]); printf("产品是: "); product(arr, size); return 0; }
输出结果
如果运行上面的代码,它将生成以下输出-
产品是: 8 24 48 80 120 168