我编写了这个程序来计算标量乘积并找出向量v的最小数和最大数(+位置数)。除了minimum_number函数之外,一切正常。它找到向量v内的最小数字和位置,但是当位置在v [0]时-----在1它显示一个非常长的数字。我不确定为什么会这样。请非常感谢你
int scalar_produc(int *v,int *w,int n)
{
int i = 0;
int sp;
int sp2 = 0;
for(i= 0; i < n; i++)
{
sp = v[i] * w[i];
sp2 = sp2 + sp;
}
return sp2;
}
int lowest_number(int *v,int n)
{
int i = 0;
int low = v[i];
int position;
for(i = 0; i < n; i++)
{
if(v[i] < low)
{
low = v[i];
position = i;
}
}
printf("The lowest number is: %d \n", low);
printf("The position of it: %d \n",position+1);
}
int biggest_number(int *v, int n)
{
int i = 0;
int position;
int biggest = v[i];
for(i = 0; i < n; i++)
{
if(v[i] > biggest)
{
biggest = v[i];
position = i;
}
}
printf("The biggest number of the vector 'v' is: %d \n",biggest);
printf("The position of the biggest number: %d \n", position+1);
}
int main()
{
int n,i;
int *v,*w;
printf("Enter the number of vectors you would like to enter: \n");
scanf("%d",&n);
v = (int*) malloc(sizeof(int) *n);
w = (int*) malloc(sizeof(int) *n);
printf("Enter the vectors: \n");
for(i = 0; i < n ;i++)
{
printf("v[%d]: \n",i+1);
scanf("%d",&v[i]);
printf("w[%d]: \n",i+1);
scanf("%d",&w[i]);
}
printf("The scalar product: %d \n",scalar_produc(v,w,n));
lowest_number(v,n);
biggest_number(v,n);
free(v);
free(w);
return 0;
}
答案 0 :(得分:2)
您没有初始化position
。因此,如果最小值是第一个值,则position
的值未定义。
将其初始化为0,它应该可以正常工作。
int i = 0;
int low = v[i];
int position = 0;