简体   繁体   中英

what is error in this code: C++ Check Whether Number is Even or Odd

I wrote the code below in c++ Check Whether Number is Even or Odd. When a user input 25 or 11 the program identifies it as an even number it seems that it took only if and neglect else statement在此处输入图片说明

even() inputs n from the user, but doesn't return it. Add a return statement at the end and you should be OK:

int even()
{
    int n;
    count << "input number:" << endl;
    cin >> n;
    return n; // Here!
}

What you probably want is:

bool even(int number) {
    return (number % 2) == 0;
}

int main() {
    int n;
    std::cout << "input number:" << endl;
    std::cin >> n;
    if(even(n)) {
        std::cout << "The number is even." << std::endl;
    }
    else {
        std::cout << "The number is odd." << std::endl;
    }
}

As mentioned your even() function missed to return a value at all (which causes undefined behavior ).

Though even (no pun!) if you get that right the only purpose of your even() function seems to get an input value and not calculating anything about the nature ( even / odd ) of that value.
This might be quite confusing for anyone reading your code.

If you just want to have a function to take input just name it so:

int takeNumberInput() {
 // ^^^^^^^^^^^^^^^
    int n;
    count << "input number:" << endl;
    cin >> n;
    return n;
}

The problem is that your even() function doesn't have a return. If you want to keep the format I'd suggest your replace your even() with getInput().

#include <iostream>
using std::cout; using std::cin; using std::endl;
int getInput(){
    int theInput;
    cin >>theInput;
    return theInput;
}
int main(){
    int number;
    std::cout << "input number:";
    number = getInput();
    if(number%2 == 0) {
        cout << "The number is even." << endl;
    }
    else {
        cout << "The number is odd." << endl;
    }
}

The problems are

1)
if (num |%2 == 0)       //This line won't even compile. There is a syntax error
2)
int even() not returning a value.

Make sure your code compile, and then post it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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