【问题标题】:Why doesn't my program stop when I press 0? C program为什么我按 0 时程序没有停止? C程序
【发布时间】:2015-06-27 18:03:15
【问题描述】:

我做了一个简单的程序,询问你是否可以进入酒吧。然后继续问你愿意花多少钱,然后问你第一次买多少钱。它继续询问您是否想购买更多,但是如果我不想购买更多,我可以输入值“0”,但是当我输入“0”时它不会关闭程序。

代码如下:

#include <stdio.h>

int main() {
int age, legal = 18;
float money, buy;

    printf("At the bar the security must ID the customers that look underage, what is your age?: ");
    scanf("%d", &age);

        if(age < legal){
            printf("\nYou are not allowed!\n");
        }

        else if(age >= legal){
            printf("\nYou may enter, and buy whatever you wish!\n");

            printf("\nHow much money are you willing to spend tonight?: ");
            scanf("%f", &money);

            printf("\nWith the %.2f dollars you want to spend tonight what is the price of food or beverage you wish to buy first?: ", money);
            scanf("%f", &buy);

            money = money - buy;

            while(money > 0 || buy==0) {
                printf("\nYou now have %.2f dollars remaining, what else would you like to buy? (Press 0 to stop if you don't wish to buy any more!!): ", money);
                scanf("%f", &buy);
                money = money - buy;
            }
                if(money == 0){
                    printf("\nYou have spent all the money that you wished to spend at the bar, we hope you enjoyed your stay!!\n");
                }

                else if(money > 0){
                    printf("\nYou still have %.2f dollars left, We hope you enjoyed your stay at the bar!!\n");
                } 

        }       
}

【问题讨论】:

  • 请避免将floatdouble 用于金钱,因为它们给出的比较不准确。使用int 以美分工作,格式为 dollars.cents 用于输出。拆分. 上的任何输入字符串以将其转换为美分。

标签: c


【解决方案1】:

你的 while 循环是错误的。它说当钱不为零时,或者当购买为零时,询问支出金额。

应该说while(money != 0 &amp;&amp; buy &gt; 0),这样只要他们有钱并且正在消费(购买高于零)就会询问消费金额。

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多