Code returning "-Nan"

Asked

Viewed 29 times

1

I made a code that performs 2 functions:

  1. calculates the average wage of an enterprise
  2. calculates the salary difference of each employee for the average wage

When executed, an error occurs in the return of function 2 (exibeDifMedia), because the "-nan". When I do the same calculation that is in direct function in main, it displays the correct value. I believe it is some problem in the construction of the function, but I am not able to find.

Someone to give me a light?

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

float calcMedia(float vet[], int tam) {
    float media, soma = 0;
    int i;

    for (i=0; i<tam; i++) {
        soma = soma + vet[i];
    }
    
    media = (float)soma/tam;
    
    return media;
}

float exibeDifMedia (int vInsc[], float vSal[], int num) {
    float difmedia, mediasal;
    int i;

    for (i=0; i<num; i++) {
      
        difmedia = mediasal - vSal[i];
            
    }

    return difmedia;
}

int main(void){
    int vInsc[6] = {1010,1020,1030,1040,1050,1060};
    float vSal[6] = {1000.00,4020.00,900.00,10400.00,20000.00,1000.00};
    float mediasal, difsal;
    int i;
    
    mediasal = calcMedia(vSal, 6);
    printf("A media dos salários é de %.2f\n", mediasal);

    for (i = 0 ; i <= 5; i++) {

        printf("\nsalário do funcionário [%d] = %.1f\n",vInsc[i], vSal[i]);
        difsal = exibeDifMedia(vInsc, vSal, 6);
        printf("\nDiferença de salário do funcionário [%d] para a média = %.1f\n",vInsc[i], difsal);
    }
    
    return 0;
}
  • In function exibeDifMedia you use the variable mediasal without having assigned a value to it. Also note that your calculation is within a loop and therefore you overwrite the calculated value at each cycle and the return of the function will be the last calculated value.

  • got it! I’ll do the flares here! Thank you!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.