【发布时间】:2025-12-23 01:25:13
【问题描述】:
我是 C 新手,正在尝试为我的 C 编程课程中的作业制作一个简单的银行系统。我决定在 while 循环中使用 switch 语句。该程序在 Visual Studio 中运行时没有错误消息,但行为非常奇怪。这是作业:
“制作一个简单的银行系统。从程序开始询问储蓄账户的起始余额。从那里它需要询问应该修改哪个账户:储蓄、支票、贷款和信贷。 支票需要设置250美元。这是支票账户中可用于支付账单的资金。 贷款需要设置为9000美元。这是贷款所欠的钱。这是一张账单。 信用额度需要设置为 500 美元。这是所欠的信用卡余额。这是一张账单。 该程序应该(在询问要修改哪个帐户之后)允许用户在该部分内转移资金。 示例:您在 Checking 中,您是要支付贷款还款、信用卡还款、将钱从 Checking 转移到储蓄还是返回主菜单。 检查是你的中心点。您可以通过支票将钱转移到任何地方,但您不能直接从 Savings 支付账单。”
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int savings;
int checking = 250;
int loans = 9000;
int credit = 500;
int moneyMover;
char choice = 'y';
int service;
int service2;
printf("Welcome to C-Bank!\n\n");
printf("What is the current balance for savings? ");
scanf("%d\n", &savings);
printf("Thank you. \n\n");
while (choice == 'y')
{
printf("Which account or bill would you like to manage? \nPress '1' for Savings, '2' for Checking, '3' for Loans, or '4' for credit. Else, press any other key to exit.");
scanf("%d\n\n", &service);
switch (service)
{
case 1:
printf("Welcome to your savings account. Your current balance is %d. \n", savings);
printf("Please choose from the following: \nWould you like to (1) make a deposit, (2) make a transfer to checking, or (3) return to the main menu.\n");
scanf("%d", &service2);
if (service2 == 1)
{
printf("Enter deposit amount: \n");
scanf("%d \n", &moneyMover);
savings = savings + moneyMover;
printf("Your new balance is: %d\n", savings);
}
break;
default:
break;
}
printf("Would you like to choose another service? If so, press y, else press any other key.\n");
scanf(" %c", &choice);
}
printf("Thank you for using C-Bank. Come back soon!");
system("PAUSE");
return 0;
}
程序运行时没有错误消息,但行为怪异。当您输入初始储蓄金额时,在您按下“y”之前什么都不会发生,此时它 显然跳入了while循环,跳过了switch语句,并等待你再次选择。或者,如果您输入另一个数字,它将快速显示其余的 printf 语句并结束程序。其他奇怪的事情发生了,实在是太多了。
【问题讨论】:
-
欢迎来到 Stack Overflow。请阅读the help pages、the SO tour、阅读how to ask good questions,以及this question checklist。最后请学习如何创建minimal reproducible example 向我们展示。
-
可能猜测关于您的问题,您可能正在阅读您没想到的换行符。请记住,您按下以结束输入的
Enter键也会放入输入缓冲区(作为换行符)供您的程序读取。 -
对不起,显然我删除了我附加的代码。堆栈溢出也是新手
-
贴出的代码无法编译!除其他外,它缺少声明:
#include <stdlib.h>函数:system()
标签: c loops switch-statement