简体   繁体   English

在数组C中找到数字的总和

[英]Find the sum of numbers in an array C

I have researched for over an hour on this topic and I had no luck so I decided to go ahead and ask this question here. 我已经对该主题进行了一个多小时的研究,但我没有运气,所以我决定继续在这里提出这个问题。 I have been figuring out how find the sum of 10 different numbers from the array after I type numbers on program. 我一直在弄清楚如何在程序上键入数字后从数组中找到10个不同数字的总和。 For example, it asks you to type 10 different numbers and they would be all added up after they are typed out in an array. 例如,它要求您键入10个不同的数字,并在数组中键入它们后将它们加在一起。 Here is the code. 这是代码。 The top part is function. 顶部是功能。 The bottom part is from main(). 底部来自main()。 Any helps would be heavily appreciated. 任何帮助将不胜感激。

void addNum(int z[])
{
    int sum = 0;
    int i;

    //scanf("%d", &z[i]);

    sum = sum + z[i];

    printf("\nThe sum of numbers you entered is %d.\n", sum);
}

........... ...........

int z[10];
int i;
int num = 0;

printf("Please enter 10 different numbers: \n");

for(i = 0; i < 10; i++)
{
    z[i] = num;
    scanf("%d", &num);
}

printf("\nThe numbers you entered were: ");

for (i = 1; i <= 10; i++)
{
    printf("%d ", z[i]);
}
printf("\n");

//scanf("%d", z[i]);

addNum(z[i]);

You should do the adding in your function 您应该在函数中进行添加

void addNum(int z[], int sizeOfArray)
{
int sum = 0;

//scanf("%d", &z[i]);
for(int i = 0; i < sizeOfArray; i++){
   sum += z[i];
}
printf("\nThe sum of numbers you entered is %d.\n", sum);
}

Pass in the array in the main with the array size 通过数组大小在主数组中传递

addNum(z,10);

In your code use pass by reference and not pass by value. 在您的代码中,请使用按引用传递而不是按值传递。

When you call "addNum(z[i])" , i is 11 and what you are passing is z[11] which will be garbage at first place but you are passing only value of one variable which is not what you wanted. 当您调用“ addNum(z [i])”时,我是11,而您要传递的是z [11],这在第一位将是垃圾,但是您仅传递了一个不是您想要的变量的值。

What you want to pass is the address of the array either "z" or "&z[0]" . 您要传递的是数组“ z”或“&z [0]”的地址。 Along with the size of array, so the function knows how many member variables in array. 随着数组的大小,因此该函数知道数组中有多少个成员变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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