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

时间:2017-10-16 04:48:11

标签: c++ while-loop return boolean do-while

前身,我刚刚开始了我的第一个编码课,所以请原谅我,如果我的错误很明显。我现在需要做的就是使用程序员定义的函数来询问整数并读出错误消息,直到输入正确的输入,然后读出正确的输入。

#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循环切换到一个do-while /其他我能想到的东西,但我现在拥有的是我最接近的东西。当我输入一个无效的整数时,我得到了正确的响应,但是当我输入一个有效的整数时,无论我输入什么有效整数,它都会打印出“你选择'1'”。我已经尝试了所有我知道的但现在我很难过。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

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