我无法弄清楚错误在哪里。当我尝试运行该程序时,它不会通过选择,而是在要求选择后直接进入程序末尾。并且,它还在 Visual C++ 编译器的“显示生成的输出”中给出了一些警告。有人可以帮我解决这个问题吗?
#include <stdio.h>
int main ()
{
int card_number, choice, withdraw, deposit;
float amount = 3000.00, new_amount = 0;
char password;
printf("Enter the card number: ");
scanf("%d", &card_number);
printf("Enter the Password: ");
scanf(" %c", &password);
printf("\n\n");
printf("\n\t***********************************");
printf("\n\t* MENU *");
printf("\n\t* 1. Check Balance *");
printf("\n\t* 2. Withdraw *");
printf("\n\t* 3. Deposit *");
printf("\n\t* 4. Exit *");
printf("\n\t* *");
printf("\n\t***********************************");
printf("\n\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1)
{
printf("Current balance on your account: %f\n", amount);
}
else if (choice == 2)
{
printf("Enter the amount you want to withdraw: ");
scanf("%d", &withdraw);
if (withdraw > amount)
{
printf("You don't have sufficient balance");
}
else
{
new_amount = amount - withdraw;
printf("Current balance on your account: %f\n", new_amount);
}
}
else if (choice == 3)
{
printf("Enter the amount you want to deposit: ");
scanf("%d", &deposit);
amount = amount + deposit;
printf("Current balance on your account: %d\n", amount);
}
else if (choice == 4)
{
printf("Thank you for using our service\n\n");
}
return 0;
}
最佳答案
大概您希望密码的长度超过一个字符,因此您需要一个“字符串”而不是单个 char
。不幸的是,C 没有字符串类型,但它有足够好的 char
数组。与其通过 scanf("%c",&password);
请求字符,不如通过 scanf("%s",&password);
请求“字符串”。 但是,password
必须定义为一个长度足以保存密码的char
数组。[1]
这导致您的程序“跳到末尾”的原因是因为 %c
只读取输入的一个字符。您可能输入了几个字符。稍后在程序中,您尝试通过 %d
读取 int
,它不能使用密码的非数字,因此 scanf()
调用失败,但您没有检查这些调用的返回值,因此您的代码不知道这些失败。
[1] 实际上,password
必须足够长以容纳用户决定输入的任何内容。实际上,您应该研究使用格式宽度(例如 %20s
)来防止数组溢出,这是一个严重的安全漏洞。但由于这是一项家庭作业,我们假设这些细节目前并不重要。
关于使用 if 和 else if 的简单 ATM 机的 c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442991/