c - Objective C - 总结 int 数组中的元素

标签 c arrays integer sum

好吧,我有一个如下所示的 int 数组:

int money[] = {};

然后我通过执行 scanf 将值添加到该数组,然后使用 for 循环将每个 scanf 值添加到数组,一次一个数字:

for (int i = 0; i < 1; i++)
{
    money[i] = currentPrice;
}

因此,在执行此操作几次(使用 scanf)后,我的数组如下所示:

money[] = {50, 75, 1, 40, 4};

如何使用 for 循环遍历列表中的所有元素并将它们添加在一起并打印出来?

int total = blablabla.......
printf(total);

最佳答案

int total = 0;
for (int i = 0; i < arrayCount; i++) {
    total += money[i];
}

printf("%i", total);

请注意,您需要保留对数组中整数数量的引用。

我还必须指出您的代码:

for (int i = 0; i < 1; i++)
{
    money[i] = currentPrice;
}

不是向数组添加值,而是将值 currentPrice 重写到数组的第 0 个索引。因此你的数组的长度永远不会> 1。

查看this tutorial

这是使用 scanf 将整数添加到数组的基本示例:

#include <stdio.h>

#define MAX_COUNT 10

int myArr[10];
int currentCount = 0;

void addInt();

int main(int argc, const char * argv[]) {


    for (int i = 0; i < MAX_COUNT; i++) {
        addInt();
    }
    int total = 0;
    for (int i = 0; i < MAX_COUNT; i++) {
        total += myArr[i];
    }
    printf("%i", total);

    return 0;
}

void addInt() {
    int new;
    scanf("Enter num: %i", &new);
    myArr[currentCount] = new;
    // Keep reference of number of elements in array...
    currentCount++;
}

关于c - Objective C - 总结 int 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878979/

相关文章:

c - 套接字编程

c - Visual Studio 2015 显示调试断言失败

python - 将Float32格式的数据提取为int32

c - Visual Studio调试: Why does a variable show up in "Locals" but not "Watch"?

c - 为什么 Visual Studio 中的编译器不允许将参数 int N[a][b]、int M[b][a] 传递给函数?

c - C 中数组中的元素数量,不带 sizeof

c# - 将 bytearray 保存到 SQL Server 中的 VarBinary 列仅插入一个字节

javascript - 将正则表达式转换为简单数组

java - NumberFormatException 在正确的字符串上抛出?

excel - 如何在excel中创建一个公式来检查整数范围