[英]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
. 当我输入数字: 32767
7, 4, 6, 7, 9, -1
,输出为32767
。 Which is totally not true. 完全不对。 Any idea what's wrong with my sum_array
function? 知道我的sum_array
函数怎么了吗?
You need to initialize sum
to zero: 您需要将sum
初始化为零:
int sum_array(int inventory[], int num)
{
int sum = 0, index;
^^^^^^^^^^^
for(index=0; index < num; index++)
sum += inventory[index];
return (sum);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.