为什么我的while循环函数只返回'1'?

问题描述:

Precursor,我刚开始我的第一个编码课,所以如果我的错误是显而易见的,请原谅我。我现在需要做的就是使用程序员定义的函数来询问整数并读出错误消息,直到输入正确的输入,然后读出正确的输入。为什么我的while循环函数只返回'1'?

#include <iostream> 
using namespace std; 

bool evenint(int num1_par);//even integer declaration 

int main() 
{ 

int num1, correctnum1;//even integer, function call variable 

cout << "Enter an even integer between 2 and 12. \n"; 
cin >> num1; 

correctnum1 = evenint(num1); //function call 

cout << "You chose '" << correctnum1 << "'" <<endl; 


return 0; 
} 

/* 
Function: evenint 
Parameter/Return: An even integer between 2 and 12 inclusively 
Description: This function ensures the input matches parameters before 
returning its value 
*/ 
bool evenint(int num1_par) 

{ 
if (!(num1_par>=2 && num1_par<=12 && num1_par % 2 ==0))// integer must be 
between 2 and 12 inclusively 
{ 
    while (!(num1_par>=2 && num1_par<=12 && num1_par % 2 ==0)) 
    { 
      cout << "Your number is invalid, please try again. \n"; 
      cin >> num1_par; 
    } 

    return (num1_par); 
} 

else 
{ 
    return (num1_par); 
} 

} 

我已经试过交换我的if-else/while循环只是一个做,而/一切我能想到的,但我现在已经是我已经得到最接近的一次。当我输入一个无效的整数时,我得到正确的响应,但是当我输入一个有效的整数时,它会输出“你选择了'1'”,不管输入的是什么有效的整数。我尝试了我所知道的一切,但现在我很难过。任何帮助都会很棒!

+0

你的状况可能不符合你的期望,请参阅[德摩根法律](https://en.wikipedia.org/wiki/De_Morgan%27s_laws)。尽管对于你的输出你的函数返回一个'boolean',所以超过'0'的任何东西都会显示为'1',因为'true'被转换为'int'为'1'。 –

+0

你的方法'evenint(..)'返回一个'bool'值。 '真'的'int'表示是'1' –

你的函数返回一个零或一个bool。将其更改为int并且您的代码将起作用。