C функция для печати позиции элемента в массиве не работает - PullRequest
0 голосов
/ 02 октября 2019

Я пытаюсь распечатать скалярное произведение двух векторов, значения и положения элемента max в каждом векторе, а также значения и положения элемента min в каждом векторе. Однако моя функция поиска минимального значения и позиции минимального значения не работает, и я не уверен, почему, поскольку он использует тот же синтаксис, что и моя функция для поиска максимального значения и позиции максимального значения, и выводит правильное значениеномера. Вот как выглядит мой код:

#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', положение?

1 Ответ

0 голосов
/ 02 октября 2019

Ваши функции положения не работают, потому что вы не инициализируете pos в ноль в начале вашего поиска, поэтому, если наименьшее находится в нулевом входе, pos неинициализируется (и устанавливается на все, что находится в стеке, например 32766). Инициализация pos = 0 делает дело.

Кроме того, вам нужно изменить локальные переменные max и min на double, а не int. В противном случае вы сравниваете int как double,и вы получите неправильный результат.

#include <stdio.h>
#include <stdlib.h>

double findingmax(double *arr, int n){
    double 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){
    double max = arr[0];
    int pos = 0;
    for(int i = 0; i < n; i++){
        if(arr[i] > max){
            max = arr[i];
            pos = i;
        } 
    }
    return pos;
} 

double findingmin(double *arr, int n){
    double 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){
    double min = arr[0];
    int pos = 0;
    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; 
}

Производит вывод:

Scalar product=6.600000
The smallest = 1.100000
Position of the smallest = 0
The largest = 3.000000
Position of the largest = 2
The smallest = 1.000000
Position of the smallest = 0
The largest = 1.000000
Position of the largest = 0
...