-4

这是我的函数定义,用于根据两个出价之间的关系计算拍卖中的获胜者。它没有带出正确的“winningBid”,并且即使没有满足这些条件,它也经常跳到 printErrorMessage 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);
}
4

3 回答 3

3

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

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留在“随机”值,这意味着您的输出可以是任何东西。

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

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

于 2012-09-28T06:23:45.637 回答
0

在倒数第二else if我想你的意思是bid2<reservePrice,不是bid2>reservePrice

于 2012-09-28T05:55:55.843 回答
0
  • 您不处理bid2<reservePrice && bid1>=reservePrice由于比较中的错字而导致的情况。
  • 案例内部的逻辑bid2>=reservePrice && bid1>=reservePrice很可疑(例如,如果bid2<bid1,该winningBid值可能大于bid1
于 2012-09-28T06:07:34.293 回答