好吧,我有一个如下所示的 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。
这是使用 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/