c++函数不起作用

c++ function not working

本文关键字:不起作用 函数 c++      更新时间:2023-10-16

以下是我的函数定义,用于根据两个出价之间的关系计算拍卖中的获胜者。它没有显示正确的"winningBid",并且通常会跳到打印ErrorMessage 4,即使这些条件没有得到满足。

void calcWinner(string bidder1, string bidder2, string lotName, 
double bid1, double bid2, double reservePrice)
{
double winningBid;
string winningBidder;
if (bid2<reservePrice && bid1<reservePrice) 
printErrorMessage(4);
else if (bid2>=reservePrice && bid1>=reservePrice)
{
if (bid2<bid1){
winningBid=bid2+.50;
winningBidder=bidder1;}
else if (bid2>=bid1 && bid2<(bid1+.50)){
winningBidder=bidder1;
winningBid=bid1;}
else if (bid2>(bid1+.50)){
winningBidder=bidder2;
winningBid=(bid1+.50);}
}
else if (bid2>reservePrice && bid1>=reservePrice){
winningBidder=bidder1;
winningBid=reservePrice;}
else if (bid2>=reservePrice && bid1<reservePrice){
winningBidder=bidder2;
winningBid=bid2;}
printWinner(winningBidder, lotName, winningBid);
}

你真的应该用简单的英语写下你的规则,而不是代码(假设你还没有),然后试着简化它们。对于一种基本上可以归结为(我认为)的情况来说,这似乎是一个非常大的代码量

void calcWinner (string bidder1, string bidder2, string lotName,
double bid1, double bid2, double reservePrice)
{
// Error if both less than reserve.
if ((bid2 < reservePrice) && (bid1 < reservePrice) ) {
printErrorMessage (4);
return;
}
// If only ONE less than reserve, other one wins.
if (bid1 < reservePrice) {
printWinner (bidder2, lotName, bid2);
return;
}
if (bid2 < reservePrice) {
printWinner (bidder1, lotName, bid1);
return;
}
// Both at least reserve at this point, bidder1 wins if higher bid, but
// only pays bid2 + 50c.
if (bid1 >= bid2) {
printWinner (bidder1, lotName, bid2 + 0.5);
return;
}
// Bidder1 also wins if bidder2 didn't beat them by 50c or more, but
// only pays what they bid.
if (bid2 < bid1 + 0.5) {
printWinner (bidder1, lotName, bid1);
return;
}
// Otherwise, bidder2 wins, pays 50c more than bid1.
printWinner (bidder2, lotName, bid1 + 0.5);
}

这就是我构建这样的代码的方式,按照优先级递减的顺序,使用一组明确定义的规则。这样,你的英语规则和代码之间的映射就很容易了。


值得一提的是,我认为您的原始代码中至少有两个问题:

  • 首先,else if (bid2>reservePrice && bid1>=reservePrice){应该检查bid2是否在保留区下方(因此默认情况下bid1获胜)
  • 其次,else if (bid2>=bid1 && bid2<(bid1+.50)){else if (bid2>(bid1+.50)){考虑了bid2可能恰好等于bid1 + 0.5的可能性。这将导致winningBid/winningBidder处于"随机"值,这意味着您的输出可以是任何值

但我真的不会考虑回去修复它们。在我看来,实现我在代码中给出的基于先例的规则方法要好得多。虽然您的规则可能与我提供的规则不完全匹配,但要想弄清楚您应该做什么更改(与原始代码相比)要容易得多。

我在代码中的注释基本上是英语规则集,你采取的方法应该是类似的。

在倒数第二个else if上,我想你指的是bid2<reservePrice,而不是bid2>reservePrice

  • 由于比较中的拼写错误,您无法处理bid2<reservePrice && bid1>=reservePrice的情况
  • bid2>=reservePrice && bid1>=reservePrice情况下的逻辑是可疑的(例如,如果bid2<bid1,则winningBid的值可能大于bid1)