它给了我一个错误,说并不是所有的控制路径都返回值:请帮助。
int using_range()
{
int Num;
try{
cout << "Please enter a integer between 1 and 10: ";
cin >> Num;
if ((Num > 10) || (Num < 0)){
throw 77;
}
else if ((Num <= 10) || (Num >= 0)){
cout << Num << " is in range\n";
return 0;
system("pause");
}
}
catch (int x){
cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl;
system("pause");
return 0;
}
}我不知道该怎么做
发布于 2014-04-12 09:07:45
问题是您有一个后跟else if的if,但是如果这两个检查都失败了,那么默认情况下将不会返回任何内容。您的代码应该防止这种情况发生,但是编译器不够聪明,无法100%确定您永远不会在两个if检查中都失败。
try{
cout << "Please enter a integer between 1 and 10: ";
cin >> Num;
if ((Num > 10) || (Num < 0)){
throw 77;
}
else if ((Num <= 10) || (Num >= 0)){
cout << Num << " is in range\n";
return 0;
system("pause");
}
// <- if you get here, nothing is going to be returned
}另一种方法可能是将else if更改为只使用else
发布于 2014-04-12 09:39:34
所以,简单解释一下:当你有一个需要返回值的函数(在你的例子中,是一个int),当你的程序中的所有路径都这样做时,编译器会很高兴。在这段代码中,可能会出现这样一种情况,即它可能会越过您的if和else if,在这种情况下,它不会做任何事情。如果你愿意,你可以在这里抛出一个错误或者别的什么。
但我还想添加一件额外的事情,那就是在接收用户输入时添加一些保护。也就是说,确保用户输入了一个数字!
例如,目前,如果用户输入b,则输出将是0 is in range!
因此,添加另一个检查以确保:
int using_range()
{
int Num;
try{
cout << "Please enter a integer between 1 and 10: ";
cin >> Num;
// this checks if whatever the user input can be parsed as an int.
if (!cin){
cout << "please enter a number." << endl;
return -1;
}
else if ((Num > 10) || (Num < 0)){
throw 77;
}
else if ((Num <= 10) || (Num >= 0)){
cout << Num << " is in range\n";
return 0;
system("pause"); // also, this will never happen :)
}
else{
// not sure how it could get here, but maybe in weird corner cases?
return -1;
}
}
catch (int x){
cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl;
system("pause");
return 0;
}
}https://stackoverflow.com/questions/23024860
复制相似问题