这段代码中的错误是什么:C ++检查数字是偶数还是奇数

问题描述 投票:-2回答:4

我在c ++中编写了下面的代码,检查数字是偶数还是奇数。当用户输入25或11时,程序将其识别为偶数,似乎只需要忽略其他语句enter image description here

c++
4个回答
1
投票

even()从用户输入n,但不返回它。最后添加一个return语句,你应该没问题:

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

1
投票

你可能想要的是:

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

如上所述,你的even()函数完全没有返回值(导致未定义的行为)。

虽然偶数(没有双关语!)如果你做对了你的even()函数的唯一目的似乎得到一个输入值而不计算任何关于该值的性质(偶数/奇数)。 对于阅读代码的人来说,这可能会让人感到困惑。

如果你只想要一个函数来输入,只需将它命名为:

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

0
投票

问题是你的even()函数没有返回。如果你想保留格式,我建议用getInput()替换你的even()。

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

0
投票

问题是

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

确保您的代码编译,然后再次发布。

© www.soinside.com 2019 - 2024. All rights reserved.