簡體   English   中英

如何讓我的 function 只接受奇數進入我的數組,而拒絕偶數? C++

[英]How can I make my function only accept odd numbers into my array, and reject even numbers? C++

讓我先說我對函數和 arrays 相當陌生。 我必須創建 3 個函數:Function1 將是用戶輸入,Function2 將確定偶數/奇數,Function3 將顯示內容。 我已經完成了 Function1 和 Function3,並將在下面發布,但我在使用 Function2 時遇到了困難。 如果用戶輸入偶數,我現在所擁有的會給用戶一條錯誤消息,但它搞砸了,我似乎無法弄清楚。

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;
 
void getUsrInput(int num[], int size) //function for user input (function 1 of 3)
{
    int n;

    for (int i = 0; i < size; i++)
    {
        cout << "Enter five odd numbers: ";
        cin >> n; 

        num[i] = n;

        if (num[i] % 2 != 0) //if the number is odd then store it, if it is even: //function for even or odd (function 2 of 3 *doesn't work)
        {
            i++;
        }
        else
        {
            cout << "Invalid input. Please only enter odd numbers!" << endl; //let the user know to enter only odd numbers. 
        }
    }
}

int main() 
{   
    const int size = 5; //array size is 5 numbers
    int num[size]; 

    getUsrInput(num, size);

    cout << "D I S P L A Y - PART C/B" << endl;
    cout << "========================" << endl;

    for (int i = 0; i < size; i++)
    {       
        cout << num[i] << endl; //function for display (function 3 of 3)
    }
}
for (int i = 0; i < size; i++)

每次通過循環遞增i

if (num[i] % 2 != 0) {
    i++;
}

每次數字為奇數時遞增i 所以每次用戶輸入一個奇數時, i都會增加兩次。 將循環控制更改為

for (int i = 0; i < size; }

所以i只會在有效輸入時增加。

它非常適合 while 循環,並且只有在插入正常時才計數:

void getUsrInput(int num[], int size) //function for user input (function 1 of 3)
{
    int n, i=0;

    while( i < size )
    {
        cout << "Enter five odd numbers: ";
        cin >> n;

        if (n % 2 == 0) 
            cout << "Invalid input. Please only enter odd numbers!" << endl; 
        else 
            num[i++] = n;   // ok then store and count up        
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM