C语言将两个长度相同的数组下标相同的相乘
时间: 2024-05-16 14:12:39 浏览: 11
可以通过循环遍历两个数组的相同下标,将它们的元素相乘,并将结果累加到一个变量中。示例代码如下:
```c
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {6, 7, 8, 9, 10};
int len = sizeof(arr1) / sizeof(arr1[0]); // 数组长度
int result = 0;
for (int i = 0; i < len; i++) {
result += arr1[i] * arr2[i];
}
printf("The result is %d\n", result);
return 0;
}
```
在上面的代码中,我们定义了两个数组 `arr1` 和 `arr2`,它们长度相同,都是 5。然后我们定义了一个变量 `result`,用于保存相乘的结果累加值。然后通过一个循环遍历两个数组,并将它们相同下标的元素相乘,并将结果累加到 `result` 变量中。最后输出 `result` 的值即可。
相关问题
将两个长度相同的数组中各下标元素一样的相乘 用c语言
可以按照如下的方式实现:
```c
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {2, 4, 6, 8, 10};
int n = sizeof(arr1) / sizeof(int);
int product = 0;
for (int i = 0; i < n; i++) {
if (arr1[i] == arr2[i]) {
product += arr1[i] * arr2[i];
}
}
printf("Product = %d\n", product);
return 0;
}
```
这个程序首先定义了两个长度相同的数组 `arr1` 和 `arr2`,然后计算了数组的长度 `n`。接下来,程序使用一个循环遍历这两个数组中的所有元素,如果两个数组在同一个下标位置上的元素相等,则将它们的积加入 `product` 变量中。最后,程序输出 `product` 的值。
C语言程序将两个长度相同的未知数组对应下标相乘得到新数组
以下是一个简单的 C 语言程序,可以将两个长度相同的未知数组对应下标相乘得到新数组:
```c
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {6, 7, 8, 9, 10};
int result[5];
int i;
for (i = 0; i < 5; i++) {
result[i] = arr1[i] * arr2[i];
}
printf("Result array: ");
for (i = 0; i < 5; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
```
在上面的程序中,我们首先定义了两个长度相同的整数数组 `arr1` 和 `arr2`,以及一个用于存储结果的整数数组 `result`。然后,我们使用一个循环遍历两个数组,对应下标相乘并将结果存储到 `result` 数组中。最后,我们输出 `result` 数组中的所有元素。
你可以根据自己的需要修改数组的元素个数和值,以及输出格式等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)