简体   繁体   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.";

I know how to check if the numbers are odd, but unsure of how to write the rest of the code.我知道如何检查数字是否为奇数,但不确定如何编写其余代码。

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;
}

You'll want to take in the array like you mentioned, the size, and traverse through it.你会想要像你提到的那样接受数组的大小,然后遍历它。 In this case we just assume all is odd, and check for an even, if we find an even number we change the return value, stop traversing and return.在这种情况下,我们只是假设所有都是奇数,并检查偶数,如果找到偶数,我们更改返回值,停止遍历并返回。

暂无
暂无

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

相关问题 接受一个二维数组,乘以一个整数,然后在 C++ 中返回新的二维数组的函数? - Function that accepts a 2D array, multiplies it by an integer, and returns the new 2D array in C++? 在 c++ 中排序 function 使得 integer 数组中的所有元素为 0 - Sort function in c++ makes all elements in integer array 0 如何创建一个接受用户输入 n 次并返回指向数组(大小为 n+1)的指针的 function,以便我可以在全局 scope 中访问它的值? C++ - How to create a function that takes user input n times and returns a pointer to the array (of size n+1) so I can access its value in global scope? C++ 如何将函数的整数大小与数组的实际大小链接? C ++ - How do i link the integer size of the function with the actual size of an array? C++ 如何在C ++中创建大小为1位的元素数组 - how to create an array of elements with 1 bit in size in c++ 在C ++中,如何创建一个接受InputIterator的函数? - In C++, how do I create a function that accepts an InputIterator? 如何将函数应用于数组中的所有元素(在C ++模板类中) - How to apply function to all elements in array (in C++ template class) 将在 C++ 中添加任何二维整数数组的所有元素的函数模板 - Function Template that will add all elements of any 2-D integer array in C++ 在 Visual Studio 2019 C++ 中,如何扩展动态分配的数组以显示其所有元素? - In Visual Studio 2019 C++, how can I expand a dynamically allocated array so that all of its elements are displayed? 编写一个接受一维数组并计算元素总和并显示它的C ++函数 - Write a C++ function that accepts a 1-D array and calculates the sum of the elements, and displays it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM