1
我做了一個簡單的程序,問你是否可以進入酒吧,如果你的年齡。然後繼續問你願意花多少錢,並在詢問你第一次購買多少錢後。它繼續詢問您是否想要購買更多,但是如果我不想購買更多,我可以輸入值「0」,但是當輸入「0」時它不會關閉程序。當我按0時,爲什麼我的程序不能停止? C程序
的代碼如下:
#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");
}
}
}
請避免使用'float'或'double'作爲金錢,因爲它們會給出不精確的比較。使用'int'工作在美分,格式爲* dollars.cents *作爲輸出。拆分'.'上的任何輸入字符串將其轉換爲分。 –