How can I subtract from an array with multiple positions with the same number in C?

1

The activity asks me to report a number of wagons and then asks me to assign a weight to each of them. I calculate the average of these weights and then subtract the average of the weights of each one of them to reach a common weight.

Here is where the number of wagons and their respective weights are reported:

int boxCarsQuantity;
int readValue
int numberPosition = 0;
int arrayWeight[0];
int sum=0;
int average=0;

    printf("Insira a quantidade de vagões\n");
    scanf("%d",&boxCarsQuantity);
    for(int i = 0; i<boxCarsQuantity; i++)
    {
        printf("Insert the weight of a Boxcar\n");
        scanf("%d",&readValue);
        arrayWeight[numberPosition] = readValue;
        sum=sum+arrayWeight[numberPosition];
        numberPosition++;
}

Here I calculate the average weight of the wagons:

    average=sum/boxCarsQuantity;

And here is where I display the average, and this is where I should display how much I should subtract from each wagon so that it reaches a common weight between the wagons:

    printf("A média é: %d\n",average);

    for(int e=0; e<boxCarsQuantity; e++)
    {
    printf("%d\n",arrayWeight[numberPosition2]-average);
    numberPosition2++;
    }

However, the last part is not running correctly, as I'm not sure how to subtract the positions of an array. How can I do this?

    
asked by anonymous 03.01.2019 / 18:09

1 answer

2

As the comments have already said, your array has size 0, you can not store values in it. You need to set the array to a size large enough to store all values, or set the size of the array at runtime with malloc.

int boxCarsQuantity;
int *arrayWeight;

printf("Insira a quantidade de vagões\n");
scanf("%d", &boxCarsQuantity);
arrayWeight = (int*) malloc(sizeof(int) * boxCarsQuantity);

Other tips: Declare average as double type to get results from floating-point divisions, and use the for iterator to access array positions, there is no reason to declare numberPosition.

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

int main()
{
    int boxCarsQuantity;
    int readValue;
    int *arrayWeight;
    int sum = 0;
    double average = 0;

    printf("Insira a quantidade de vagões\n");
    scanf("%d", &boxCarsQuantity);
    arrayWeight = (int*) malloc(sizeof(int) * boxCarsQuantity);

    for(int i = 0; i < boxCarsQuantity; i++)
    {
        printf("Insert the weight of a Boxcar\n");
        scanf("%d", &readValue);

        arrayWeight[i] = readValue;
        sum += arrayWeight[i];
    }

    average = (double) sum/boxCarsQuantity;
    printf("A média é: %.2f\n", average);

    for(int j = 0; j < boxCarsQuantity; j++)
    {
        printf("%.2f\n", arrayWeight[j] - average);
    }

    return 0;
}
    
03.01.2019 / 19:02