【发布时间】:2019-10-26 21:13:16
【问题描述】:
在这方面遇到的麻烦比我应该的要多。我正在构建一个非常简单的银行菜单界面,用户可以在其中查看余额、存款、取款或退出菜单。 case 1、case2 和 case3 似乎工作正常,但无论我在 Google 上尝试什么,case 4 都无法正常工作。
在当前版本中,case 4 中的 printf() 语句出现,然后似乎没有其他任何事情发生,直到我输入其他选项之一 (1 - 3) 两次,此时循环将自动循环使用第二个输入。我尝试了getchar(),但这似乎不起作用(或者我没有正确实现它)。
为什么会出现这种行为,我该如何解决?
代码如下:
#include <stdio.h>
#include <cs50.h>
double deposit(double a, double b);
double withdraw(double a, double b);
int main(void)
{
int resume = 1;
int user_input = 0;
double user_balance = 10.00;
printf("Welcome to UBank!\n");
while (resume)
{
printf("\n====================\n");
printf("Select an operation:\n\n1. Show Balance\n2. Make a Deposit\n3. Make a Withdrawal\n4. Quit\n"
"====================\n\n");
scanf("%d", &user_input);
int quit_character = 0x00;
double deposit_amount = 0.00;
double withdraw_amount = 0.00;
switch (user_input)
{
case 1:
printf("Balance: $%.2lf\n", user_balance);
break;
case 2:
printf("How much would you like to deposit?\n");
scanf("%lf", &deposit_amount);
user_balance = deposit(user_balance, deposit_amount);
break;
case 3:
printf("How much would you like to withdraw?\n");
scanf("%lf", &withdraw_amount);
user_balance = withdraw(user_balance, withdraw_amount);
break;
case 4:
printf("Press Enter to finish banking or any other key to continue.\n");
scanf("%d\n", &quit_character);
if (quit_character == 0x0A)
{
resume = 0;
}
break;
}
}
}
double deposit(double a, double b)
{
if (b > 0 && b < 10000)
{
return a + b;
}
else
{
printf("Please enter a valid amount. (0.01 - 9999.99)\n");
return a;
}
}
double withdraw(double a, double b)
{
if (b > 0 && a - b >= 10)
{
return a - b;
}
else if (b <= 0)
{
printf("Withdrawal amount must be greater than $0.00.\n");
}
else if (a - b < 10)
{
printf("Withdrawal amount invalid. Remaining balance must be $10.00 or more.\n");
}
return a;
}
【问题讨论】:
-
您不能使用
%d格式来读取通用字符。尤其不是任何空格字符(换行符是空格字符),因为%d格式scanf函数将跳过(并忽略)前导空格字符。 -
你需要学习如何检查scanf的返回值来检测错误。
-
@Someprogrammerdude 抱歉,C 新手,你有什么建议?
标签: c switch-statement cs50 enter