期望:我想计算 int
类型数组中可用元素的数量,其中 0
可以是一个元素。
程序输出如下:
Total Element :6
预期输出:
Total Element :9
代码:
#include <stdio.h>
int main() {
int a[50] = { 1, 2, -3, 0, 0, 6, 7, -8, 0 };
int count = 0;
int i = 0;
for (i = 0; i < 50; i++) {
if (a[i]) {
count++;
}
}
printf("Total Element :%d ", count);
return 0;
}
注意:我想计算数组中元素的总数。我不想计算数组的大小。
最佳答案
I want to count Total number of element in array
就目前而言,您不能。
在 C 中,数组不知道哪些元素曾被使用过或未被使用过。
如果无法定义标记、停止值,但您知道初始化程序,您可以执行以下操作:
#include <stddef.h> /* for size_t */
#include <stdio.h>
#define ARRAY_INITIALISER {1, 2, -3, 0, 0, 6, 7, -8, 0}
int main()
{
int a[50] = ARRAY_INITIALISER;
size_t count;
{
int tmp[] = ARRAY_INITIALISER;
count = sizeof tmp / sizeof *tmp;
}
printf("Total number of elements 'used': %zu\n", count);
return 0;
}
关于c - 如何计算 0 可以是元素的 int 类型数组中的元素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46861611/