even()
从用户输入n
,但不返回它。最后添加一个return语句,你应该没问题:
int even()
{
int n;
count << "input number:" << endl;
cin >> n;
return n; // Here!
}
你可能想要的是:
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;
}
问题是你的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;
}
}
问题是
1)
if (num |%2 == 0) //This line won't even compile. There is a syntax error
2)
int even() not returning a value.
确保您的代码编译,然后再次发布。