gpt4 book ai didi

c - 函数在 switch 语句中被不正确地执行/重复。其余代码不执行

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:22 24 4
gpt4 key购买 nike

到目前为止,main() 执行正常,while 循环执行正常。如果我输入了错误的 PIN,程序会立即停止执行。否则,程序将继续执行其余部分。

我决定测试一个函数,transfer(),这就是我遇到问题的地方。传递函数只对 printf 语句正确执行。程序没有等待我输入要在哪个帐户上进行转账,而是跳回到 transfer() 的开头并不断重复……

transfer() 中的 switch 语句甚至没有执行!为什么?

//This program will mimick an ATM machine
//It will do deposits, withdrawals, and authentication

//Function Declarations
//float withdrawal();
//float deposit();
float transfer ();
void decision ();

float checking = 15050.00;
float savings = 8200.83;

#include <stdio.h>

int main ()
{
int PIN;
printf ("Welcome to Wells Fargo 24HR Teller!\n");
printf ("Enter Your 4-Digit PIN \n");
scanf ("%d", &PIN);

while (PIN == 2016) {
decision (); //this starts the ATM choices user can select
}
if (PIN != 2016) {
printf ("AUTHENTICATION FAILED");
}
return 0;
}

void decision ()
{

printf ("I want to:\n");
printf ("A) Make a Transfer\n");
//printf("B) Make a Deposit\n");
//printf("C) Make a Withdrawal\n");
//printf("D) Exit\n");

char selection;
scanf ("%c", &selection);

switch (selection) {
case 'A':
transfer ();
//case 'B': deposit();
//case 'C': withdrawal();
//case 'D': break;
}
}

float transfer ()
{
float transamt;
float chekbal;
float savbal;
printf ("Transfer Amount? \n");
scanf ("%f", &transamt);
printf ("\n Transfer Amount of %f", transamt);


printf ("\n Which Account? \n");
printf (" A) Checking \n");
printf (" B) Savings \n");

/*Right after this point, execution goes back to beginning of decision()
program execution doesn't go through switch statement */
char confirm;
scanf ("%c", &confirm);

switch (confirm) {
case 'A':
chekbal = (transamt + checking);
printf ("Checking Balance is Now %f", chekbal);
break;

case 'B':
savbal = (transamt + savings);
printf ("Savings Balance is Now %f", savbal);
break;
}

return 0;
}

最佳答案

问题是带有 %c 转换说明符的 scanf 不消耗空格,参见 here :

All conversion specifiers other than [, c, and n consume and discard all leading whitespace characters

输入转账金额后回车,stdin中插入一个换行符,scanf("%c", &confirm)看到后存入confirm,即confirm 现在包含换行符。要明确地看到这一点,请尝试将 case '\n': 添加到 switch(confirm) 语句;您会看到 switch 语句实际上正在执行,只是 confirm 的值与您之前的任何情况都不匹配。最好始终将 default: 标签添加到 switch 语句以捕获任何意外值。

解决方案非常简单,您只需要在格式字符串中的 %c 之前添加任意空白字符,因为(来自上面的同一来源),

any single whitespace character in the format string consumes all available consecutive whitespace characters from the input

因此,scanf("%c", &confirm); 将在读取将分配给 确认

关于c - 函数在 switch 语句中被不正确地执行/重复。其余代码不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39135206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com