该程序应该采用2个数组并在数组中的每个元素上执行点积。
如果n的索引小于5,我的程序就可以了。但是,一旦数组的索引大于5,则第一个数组中的第一个元素是错误的(我通过在函数中添加printf语句来检查)。我不知道如何修复这个错误。
#include <stdio.h>
void multi_vec(int *v1, int *v2, int *v3, int n);
int main(void)
{
int n, i;
int v1[n];
int v2[n];
int v3[n];
printf("Enter the length of the two vectors\n");
scanf("%d", &n);
printf("Enter numbers for the first array\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
}
printf("Enter numbers for the second array\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &v2[i]);
}
multi_vec(v1, v2, v3, n);
for (i = 0; i < n; i++) {
printf("%d", v3[i]);
}
printf("\n");
return 0;
}
void multi_vec(int *v1, int *v2, int *v3, int n)
{
int i;
for (i = 0; i < n; i++) {
*(v3+i) = *(v1+i) * *(v2+i);
}
}
答案 0 :(得分:1)
更正代码
#include <stdio.h>
void multi_vec(int *v1, int *v2, int *v3, int n);
int main(void)
{
int n, i;
printf("Enter the length of the two vectors\n");
scanf("%d", &n);
int v1[n],v2[n],v3[n]; //you didn't initialize n
printf("Enter numbers for the first array\n"); //printf statements had extra ',n'
for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
}
printf("Enter numbers for the second array\n"); //printf statements had extra ',n'
for (i = 0; i < n; i++) {
scanf("%d", &v2[i]);
}
multi_vec(v1, v2, v3, n);
for (i = 0; i < n; i++) {
printf("%d ", v3[i]);
}
printf("\n");
return 0;
}
void multi_vec(int *v1, int *v2, int *v3, int n)
{
int i;
for (i = 0; i < n; i++) {
*(v3+i) = *(v1+i) * *(v2+i);
}
}