繁体   English   中英

我如何创建一个接受整数数组及其大小并返回 true 的 c++ 函数 isOdd 是所有数组元素都是奇数

[英]How could I create a c++ function isOdd that accepts an integer array and its size and returns true is all of the array elements are odd

if ( n % 2 == 0)
    cout << n << " is even.";
  else
    cout << n << " is odd.";

我知道如何检查数字是否为奇数,但不确定如何编写其余代码。

bool isOdd(int int_arr[], int arr_size)
{
    bool is_all_odd = true;
    for(int i = 0; i < arr_size; i++)
    {
        if(int_arr[i] % 2 == 0)
            {
                is_all_odd = false;
                break;
            }
    }
    
    return is_all_odd;
}

你会想要像你提到的那样接受数组的大小,然后遍历它。 在这种情况下,我们只是假设所有都是奇数,并检查偶数,如果找到偶数,我们更改返回值,停止遍历并返回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM