c++ 为什么while循环允许我连续输入值,但循环什么也不做

c9qzyr3d  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(115)
#include <iosteam>

int main(){
int money, coupons, chocolate, ogCoupons, newChocolate, couponsUsed;

std :: cout << "How many chocolate bars do you want to buy? " << std :: endl;
std :: cin >> money;

coupons = money;
chocolate = money;
ogCoupons = coupons;

std :: cout << "\nYou got " << coupons << " coupons." << std :: endl;

while(coupons >= 6)
    {
        coupons -= 6;
        couponsUsed = (ogCoupons - coupons); //I think problem lies here
        chocolate++;
        newChocolate = couponsUsed;
        coupons += newChocolate;
        ogCoupons = coupons;
    } 

std :: cout << "\nYou have " << coupons << " coupons left and " <<  chocolate << " chocolate bars." << std :: endl;

return 0;
}

代码应该这样做:如果你有22美元,你可以先买22块巧克力,这会给予你22张优惠券,你可以用其中的18张换3块巧克力,现在总共是25张,这3块巧克力给你3张优惠券,现在总共是7张,这给你足够的优惠券再买一块巧克力,再用一张优惠券,现在总共有26块巧克力棒和2张剩余的优惠券。
问题出在while循环中。当我试图减去couponsUsed中的两个变量时,循环让我输入随机整数和字符,但什么也不发生。

wwwo4jvm

wwwo4jvm1#

您的代码令人困惑。也许可以这样想:

while (coupons >= 6) {
     // So far, so good. If we're in this loop, we have enough
     // coupons to trade for a chocolate bar. So buy exactly one:
     ++chocolate;
     coupons -= 6;

     // And because we bought a chocolate bar, we get one more coupon:
     ++coupons;
}

我没有测试过,但这更容易阅读和理解。给予吧。
编程中的一个常见错误是把问题弄得太复杂。如果事情变得毫无意义,那么就退一步,问问自己是否在保持简单。
另外,最好在你将要使用变量的时候定义它们。你在函数的顶部定义了一堆你最终并不真正需要的变量,或者如果你需要的话,只在循环中定义。所以在你使用它们的地方声明它们。我会把顶部写得更像这样:

int money;

std :: cout << "How many chocolate bars do you want to buy? " << std :: endl;
std :: cin >> money;

// Chocolate bars are $1, so we get 1 bar per dollar
// and 1 coupon for each bar we buy.
int coupons = money;
int chocolate = money;

你完全不需要其他变量。

相关问题