我正在尝试调试用于验证用户输入的递归函数,并在输入正常时返回一个值。该函数如下所示:
double load_price()
{
double price;
Goods * tempGd = new Goods();
cin >> price;
while (!cin)
{
cin.clear();
#undef max
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
cin >> price;
} // endwhile
if (!tempGd->set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
load_price();
}
else
{
delete tempGd;
return price;
}
}
商品类的方法set_price()如下所示
bool Goods::set_price(double price)
{
if (price> 0)
{
priceSingle_ = price;
priceTotal_ = price* amount_;
return true;
}
return false;
}
我尝试在纸上绘制问题,但我的所有图表看起来都像我的功能已经看起来一样。我认为回报有一些问题,但我不知道在哪里。
非常感谢帮助。
答案 0 :(得分:5)
您没有使用递归调用的返回值。你需要这样做:
return load_price();
答案 1 :(得分:1)
谁和你谈过使用递归来解决这个问题?
#undef max
double load_price()
{
for(;;) {
double price;
cin >> price;
if (!cin)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
continue;
}
if (!Goods().set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
continue;
}
return price;
}
}