c - 我有一个c练习

标签 c arrays

我的练习是从键盘输入列表整数,并在程序末尾加0。然后打印数组的和。这是我的代码:

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

const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);

int main(int argc, char** argv) {
    int x[MAX_ITEMS], count;

    inputIntegerNumber(&x, &count);
    printf("Sum of array is %d", sumOfInteger(&x, &count));

    return (EXIT_SUCCESS);
}

void inputIntegerNumber(int* a, int* count ){
    do{
        printf("Please! input numbers: ");
        scanf("%d", a);
        *count++;
    }while((*a != 0) && (*count != MAX_ITEMS));

}

int sumOfInteger(int* n, int* count){
    int sum = 0;

    for (int i = 0; i < *count; i++)
        sum += *n;

    return sum;
}

不知道这是怎么回事?它没有给我一个与我想的相同的结果......

最佳答案

存在一些问题,例如 -

 inputIntegerNumber(&x, &count);
 printf("Sum of array is %d", sumOfInteger(&x, &count));

在这两个调用中,您都传递了 &xx 是一个 int 数组,并且您的函数需要 int *不是int (*)[]。这至少肯定给出了一个错误。

对于这两个函数,您可以直接传递数组x

在你的函数inputIntegerNumber中这个 -

 *count++;

您需要增加count的值,因此它应该是(*count)++。首先取消引用,然后增加值。

关于c - 我有一个c练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561062/

相关文章:

c - C 中的外部变量及其作用域

c - 字符串文字和指针有什么区别?

C# - winforms - 以数组形式获取 ListView 中特定列的文本

java - 有没有一种方法可以在 Java 的一个数组元素中包含多行文本?

python - 删除 bool 掩码对应的数组中的所有元素

WPF DataBinding 在绑定(bind)中指定数组索引不起作用

c - IPv6 绑定(bind)失败

c - 使用纯 C 通过 SSL (HTTPS) 的 WinInet POST?

c - 局部变长数组

java - 使用创建时提到的值创建 ArrayList