C++ 为什么我的while循环函数只返回';1';?
首先,我刚开始我的第一个编码课程,所以如果我的错误显而易见,请原谅我。我现在需要做的就是使用一个程序员定义的函数来请求一个整数并读取一条错误消息,直到输入正确的输入,然后读取正确的输入C++ 为什么我的while循环函数只返回';1';?,c++,while-loop,return,boolean,do-while,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, f
#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);
}
}
#包括
使用名称空间std;
布尔-伊文特(国际货币单位数)//偶整数声明
int main()
{
int num1,correctnum1;//偶数整数,函数调用变量
cout>num1;
correctnum1=evenint(num1);//函数调用
cout您的函数返回一个布尔值,该布尔值为零或一。将其更改为int,代码将正常工作。您的条件可能不会达到预期效果,请参见。尽管对于您的输出,您的函数返回一个布尔值,因此0
以上的任何内容都将显示为1
,因为true
转换为 int
是1
。您的方法evenint(..)
返回一个bool
值。int
表示true
是1