简体   繁体   中英

In C: function that sums items in array returning weird large number

This program is supposed to take input, put it in an array and output the item #, items in stock, and the sum of the items in the array. Here is the code:

#include <stdio.h>

#define MAX 20

void print_inventory(int inventory[], int numitems);

int input_inventory(int inventory[], int maxnum);

int sum_array(int inventory[], int numitems);

int main()
{
    int inventory[MAX];
    int num_items;

    printf("Please enter the number of items in stock. ");
    printf("Enter -1 when you are done.\n");

    num_items = input_inventory(inventory, MAX);

    print_inventory(inventory, num_items);

    return 0;
}

int input_inventory(int inventory[], int maxnum)
{
    int index=0;

    scanf("%d", &inventory[index]);
    while (index < maxnum-1 && inventory[index] != -1){
        index++;
        scanf("%d", &inventory[index]);
    }
    if (index == maxnum-1){
        printf("No room for more items.\n");
        return(index+1);
    }
    else 
        return (index);
}

void print_inventory(int inventory[], int numitems)
{
    int index;

    for (index = 0; index < numitems; index++){
        printf("Item number %d:\t\t", index+1);
        printf("Number on hand %5d\n", inventory[index]);
    }
    printf("The total number of items is %d.\n", sum_array(inventory,      numitems));

}

int sum_array(int inventory[], int num)
{
    int sum, index;

    for(index=0; index < num; index++)
        sum += inventory[index];

    return (sum);
}

When I input the numbers: 7, 4, 6, 7, 9, -1 , the output is 32767 . Which is totally not true. Any idea what's wrong with my sum_array function?

You need to initialize sum to zero:

int sum_array(int inventory[], int num)
{
    int sum = 0, index;
    ^^^^^^^^^^^
    for(index=0; index < num; index++)
        sum += inventory[index];

    return (sum);
}

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