在C语言中,将两个长度相同的一维数组中各下标相同的对应元素相乘,并将结果存放到另一个一维数组中
时间: 2024-05-08 16:20:18 浏览: 24
这个操作叫做数组元素对应相乘。可以通过以下代码实现:
```
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {10, 20, 30, 40, 50};
int result[5];
for (int i = 0; i < 5; i++) {
result[i] = arr1[i] * arr2[i];
}
for (int i = 0; i < 5; i++) {
printf("%d ", result[i]);
}
return 0;
}
```
输出结果为:10 40 90 160 250,即将 arr1 和 arr2 中对应下标位置的元素相乘,结果存放到 result 数组中。
相关问题
用c语言将两个长度相同的一维数组中各下标相同的对应元素相乘,并将结果存放到一个数组中
好的,下面是用 C 语言实现的代码:
```c
#include <stdio.h>
#define SIZE 5 // 数组长度
int main() {
int arr1[SIZE] = {1, 2, 3, 4, 5}; // 第一个数组
int arr2[SIZE] = {6, 7, 8, 9, 10}; // 第二个数组
int result[SIZE]; // 结果数组
int i;
// 将对应元素相乘并存放到结果数组中
for (i = 0; i < SIZE; i++) {
result[i] = arr1[i] * arr2[i];
}
// 输出结果数组
printf("Result array: ");
for (i = 0; i < SIZE; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
```
这个程序中,我们定义了两个长度相同的一维数组 `arr1` 和 `arr2`,以及一个用于存放结果的数组 `result`,数组长度为 `SIZE`。程序使用一个 `for` 循环遍历数组,将对应元素相乘并存放到结果数组 `result` 中,最后输出结果数组。
用c语言将两个长度相同的一维数组中各下标相同的对应元素相乘并将结果存放到另一个一维数组中
以下是一个示例代码,它将两个长度为n的数组a和b的对应元素相乘,并将结果存储在数组result中:
```c
#include <stdio.h>
int main() {
int n;
printf("Enter the length of the arrays: ");
scanf("%d", &n);
int a[n], b[n], result[n];
printf("Enter array a values: ");
for(int i=0; i<n; i++) {
scanf("%d", &a[i]);
}
printf("Enter array b values: ");
for(int i=0; i<n; i++) {
scanf("%d", &b[i]);
}
// Multiply corresponding elements of a and b and store in result
for(int i=0; i<n; i++) {
result[i] = a[i] * b[i];
}
// Print the result array
printf("[ ");
for(int i=0; i<n; i++) {
printf("%d ", result[i]);
}
printf("]\n");
return 0;
}
```
在这个示例中,我们首先读取数组的长度,然后依次读取数组a和b的值。接下来,我们使用一个循环将两个数组的对应元素相乘并将结果存储在result数组中。最后,我们打印result数组的值。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)