【发布时间】:2020-02-01 02:01:24
【问题描述】:
我正在尝试打印两个向量的标量积,即每个向量中最大元素的值和位置,以及每个向量中最小元素的值和位置。但是,我的查找最小值和最小值位置的函数不起作用,我不确定为什么,因为它使用与查找最大值和最大值位置的函数相同的语法,并且打印正确数字。这是我的代码的样子:
#include <stdio.h>
#include <stdlib.h>
double findingmax(double *arr, int n){
int max = arr[0];
for(int i = 0; i < n; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}
int findingmaxpos(double *arr, int n){
int max = arr[0];
int pos;
for(int i = 0; i < n; i++){
if(arr[i] > max){
max = arr[i];
pos = i;
}
}
return pos;
}
double findingmin(double *arr, int n){
int min = arr[0];
for(int i = 0; i < n; i++){
if(arr[i] < min){
min = arr[i];
}
}
return min;
}
int findingminpos(double *arr, int n){
int min = arr[0];
int pos;
for(int i = 0; i < n; i++){
if(arr[i] < min){
min = arr[i];
pos = i;
}
}
return pos;
}
double scalarproduct(double *v, double *w, int n){
double vw[n];
for(int i = 0; i < n; i++){
vw[i] = (v[i] * w[i]);
}
double scalprod = 0;
for(int i = 0; i < n; i++){
scalprod += vw[i];
}
return scalprod;
}
int main(){
int n;
scanf("%d", &n);
double *v;
v = (double *) malloc(sizeof(double) * n);
double *w;
w = (double *) malloc(sizeof(double) * n);
for(int i = 0; i < n; i++){
scanf("%lf", &v[i]);
}
for (int i = 0; i < n; i++){
scanf("%lf", &w[i]);
}
printf("Scalar product=%lf\n", scalarproduct(v, w, n));
printf("The smallest = %lf\n", findingmin(v, n));
printf("Position of the smallest = %d\n", findingminpos(v, n));
printf("The largest = %lf\n", findingmax(v, n));
printf("Position of the largest = %d\n", findingmaxpos(v, n));
printf("The smallest = %lf\n", findingmin(w, n));
printf("Position of the smallest = %d\n", findingminpos(w, n));
printf("The largest = %lf\n", findingmax(w, n));
printf("Position of the largest = %d\n", findingmaxpos(w, n));
return 0;
}
输入是这样的:
3
1.1
2.5
3.0
1.0
1.0
1.0
输出应该是这样的:
Scalar product=6.600000
The smallest = 1.100000
Position of smallest = 0
The largest = 3.000000
Position of largest = 2
The smallest = 1.000000
Position of smallest = 0
The largest = 1.000000
Position of largest = 0
但我的输出是这样的:
Scalar product=6.600000
The smallest = 1.000000
Position of the smallest = 32766
The largest = 3.000000
Position of the largest = 2
The smallest = 1.000000
Position of the smallest = 32766
The largest = 1.000000
Position of the largest = 32766
如何打印正确的“i”,位置?
【问题讨论】:
-
您的位置函数不起作用,因为您没有在搜索开始时将 pos 初始化为零,因此如果最小的在条目零中,则 pos 未初始化(并设置为堆栈如 32766)
-
另外,你的局部变量 max 和 min 必须声明为 double,否则你是在比较 ints 和 doubles,并返回一个向下取整的值。
标签: c arrays memory dynamic allocation