)给定 n 个整数 a1, a2, … , an ,求它们两两相乘再相加的和,即 S = a1 · a2 + a1 · a3 + · · · + a1 · an + a2 · a3 + · · · + an-2 · an-1 + an-2 · an + an-1 · an. 样例输入 4 1 3 6 9 样例输出 117
时间: 2023-09-10 11:07:44 浏览: 50
这个问题可以使用双重循环来解决,第一重循环遍历所有数,第二重循环从第一重循环的下一个数开始遍历到最后一个数,计算它们的积并累加到结果中即可。
以下是 Python 代码实现:
```python
n = int(input())
a = list(map(int, input().split()))
s = 0
for i in range(n):
for j in range(i+1, n):
s += a[i] * a[j]
print(s)
```
输入样例:
```
4
1 3 6 9
```
输出样例:
```
117
```
相关问题
蓝桥杯真题 求和 给定 n 个整数 a1· a2, · · · , an,求它们两两相乘再相加的和python
以下是求解蓝桥杯真题的Python代码:
```python
n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
for j in range(i+1, n):
ans += a[i] * a[j]
print(ans)
```
3)给定 n 个整数 a1, a2, … , an ,求它们两两相乘再相加的和,即 S = a1 · a2 + a1 · a3 + · · · + a1 · an + a2 · a3 + · · · + an-2 · an-1 + an-2 · an + an-1 · an. 样例输入
这里是使用 C 语言编写的给定 n 个整数求两两相乘再相加的和的代码:
```c
#include <stdio.h>
int main()
{
int n, a[100], i, j, sum = 0;
printf("请输入整数个数n:");
scanf("%d", &n);
printf("请输入%d个整数:", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
sum += a[i] * a[j]; // a[i]和a[j]相乘,累加到sum中
}
}
printf("两两相乘再相加的和为:%d\n", sum);
return 0;
}
```
以上代码中,我们先输入整数个数n和n个整数a1, a2, … , an,然后使用两层循环遍历每个数对,将其两两相乘再相加的结果累加到sum中。最后输出sum的值作为答案。
例如,如果输入n为4,整数为1、2、3、4,那么两两相乘再相加的和为:1x2 + 1x3 + 1x4 + 2x3 + 2x4 + 3x4 = 20。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)