使用指针编写程序,求两个向量的内积
时间: 2023-06-09 08:03:46 浏览: 57
好的,以下是使用指针编写程序求两个向量的内积的示例代码:
```c
#include <stdio.h>
int main() {
int n;
printf("请输入向量的维度: ");
scanf("%d", &n);
int vec1[n];
int vec2[n];
int inner_product = 0;
printf("请输入向量1的%d个元素: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", vec1 + i);
}
printf("请输入向量2的%d个元素: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", vec2 + i);
}
for (int i = 0; i < n; i++) {
inner_product += *(vec1 + i) * *(vec2 + i);
}
printf("向量的内积为%d\n", inner_product);
return 0;
}
```
请问还有别的问题吗?
相关问题
使用指针编写程序,求两个向量的内积,c语言,给简洁一点的代码
以下是一个简洁的C语言程序,使用指针计算两个向量的内积:
```c
#include <stdio.h>
#define N 3 // 向量的维数
int main() {
int vec1[N] = {1, 2, 3}; // 向量1
int vec2[N] = {4, 5, 6}; // 向量2
int dot_product = 0; // 内积
// 计算内积
for (int i = 0; i < N; i++) {
dot_product += *(vec1 + i) * *(vec2 + i);
}
// 打印结果
printf("向量的内积为: %d\n", dot_product);
return 0;
}
```
在此程序中,我们定义了两个长度为3的向量`vec1`和`vec2`,并使用指针遍历它们,计算它们的内积。`dot_product`变量用于存储内积的结果。最后,我们打印出内积的值。
C语言编写一个函数vec_add,接受三个指针以及向量长度作为参数,其中前两个指针用于传入需要相加的两个向量,第三个指针用于返回两个向量相加的结果,并在主函数中测试这个函数。
好的,这个问题是一个关于C语言编写函数的问题,很适合回答。下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
void vec_add(const double *a, const double *b, double *c, int n){
for(int i=0; i<n; i++){
c[i] = a[i] + b[i];
}
}
int main(){
int n = 5;
double *a = (double*)malloc(n*sizeof(double));
double *b = (double*)malloc(n*sizeof(double));
double *c = (double*)malloc(n*sizeof(double));
for(int i=0; i<n; i++){
a[i] = i;
b[i] = 2*i;
}
vec_add(a, b, c, n);
for(int i=0; i<n; i++){
printf("%lf ", c[i]);
}
free(a);
free(b);
free(c);
return 0;
}
```
这个代码实现了一个名为vec_add的函数,可以接收两个向量和一个向量长度,实现对向量的加法操作。在主函数中,先动态分配了三个数组空间,并填充了需要相加的两个向量,接着调用vec_add函数对这两个向量进行加法操作,最后输出相加后的结果。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)