簡體   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