c++获取数组非空元素个数
作者:野牛程序员:2023-12-01 17:18:52 C++阅读 2774
使用C++编写一个函数来获取数组中非空元素的个数,可以通过遍历数组并检查每个元素是否为空来实现。以下是一个简单的示例代码:
#include <iostream> // 定义获取非空元素个数的函数 int countNonEmptyElements(const int arr[], int size) { int count = 0; // 遍历数组并检查非空元素 for (int i = 0; i < size; ++i) { if (arr[i] != 0) { // 如果元素非空,增加计数 ++count; } } return count; } int main() { // 示例数组 int myArray[] = {1, 0, 3, 0, 5, 0, 7}; // 获取非空元素个数并输出 int nonEmptyCount = countNonEmptyElements(myArray, sizeof(myArray) / sizeof(myArray[0])); std::cout << "非空元素个数:" << nonEmptyCount << std::endl; return 0; }
请注意,这里假设空元素为0。如果数组中的空元素是通过其他方式表示的,需要相应地修改条件。上述代码中的 countNonEmptyElements
函数接受一个整数数组和数组的大小作为参数,返回非空元素的个数。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:基于arduino的智能调光台灯
- 下一篇:c++ 弧度值与角度值的转换