简体   繁体   中英

Why is this C Array algorithm failing on the second iteration?

I'm having trouble at the checkTotal() function. In the first iteration, it can sum everything with it's value correctly.

However during my second iteration, the values added up are not accurate and I'm not really sure where the numbers are coming from.

 int checkTotal(int numSchemes, int numComponents, int weight[numComponents][numSchemes], char **list){
     int cCounter = 0;
     int total = 0;
     while (cCounter < numComponents){
        total = total + weight[numSchemes][cCounter];
        printf("%d\n", total);
        cCounter++;
     }

     return total;
}

And this is the function that calls checkTotal

void weightInput(int numSchemes, int numComponents, int weight[numComponents][numSchemes], char **list){
    int sCounter = 0;
    int cCounter = 0;

            // iterating through the number of schemes
    while (sCounter < numSchemes){
        printf("\nMarking scheme #%d: \n", (sCounter+1));
        while (cCounter < numComponents){
            printf("\tenter %s's weight:  ", list[cCounter]);
            int theWeight;
            scanf("%d", &theWeight);
            weight[sCounter][cCounter] = theWeight;
            cCounter++; 
        }   
        //printf("%d\n", weight[sCounter][cCounter]);
        printf("THE TOTAL IS %d\n", checkTotal(sCounter, numComponents, weight, list));
        sCounter++;
        cCounter = 0;
    }
 }

The function takes a 2d array, iterates through the second dimension, and then adds up all int's to receive a total.

It successsfully sums up and returns the sum in the first iteration, but for my second iteration, it does now.

If I input 33, 22, 5, 5 for the first iteration, it will return 65.

For my second iteration, I would have (10, 5, 10, 25) but it would return 47 when it should be 50.

If anyone can help out, it would be much appreciated. Thank you in advance,

It looks to me like the logic could be potentially be back to front? You have

int weight[numComponents][numSchemes]

in the signature line, but then access it with.

weight[numSchemes][cCounter]

Should cCounter and numSchemes be the other way around?

total = total + weight[numSchemes][cCounter];

should be:

total = total + weight[numComponents][cCounter]; 

Thanks @user3629249

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM