我刚开始使用C编程,我正在使用代码块来学习。我正在研究一个简单的ATM程序,并决定在输入无效条目时使用goto函数。当我第一次使用它时,它按预期运行。但现在它不会超越其中一个陈述。代码如下。
当按下任何选项1-3时,它按预期运行,但也会继续运行选择错误部分。如果我只是尝试运行选择错误部分,它会通过它,并不断重复它。我如何阻止这种情况发生?我只需要在满足条件时运行无效选择部分,然后才能运行。谢谢!
int iSelection = 0;
float fTransAmount = 0.0;
float fBalance = 100.25;
printf("\n\n\tATM\n");
menu_options:
printf("\n1\t To Make a Deposit Press One");
printf("\n2\t To Make a Withdrawal Press Two");
printf("\n3\t To End Transaction, Press Three\n");
scanf("%d", &iSelection);
if (iSelection == 1) {
printf("\n Enter Amount to Deposit: ");
scanf("%f", &fTransAmount);
printf("\n Your new balance is: $%.2f", fBalance + fTransAmount);
} //End if for 1
if (iSelection == 2) {
printf("\n Enter Amount to Withdraw: ");
scanf("%f", &fTransAmount);
if (fTransAmount > fBalance)
printf("\n Insufficient funds, ending transaction.....\n");
else
printf("\n Your new balance is $%.2f\n", fBalance - fTransAmount);
} //End if for 2
if (iSelection == 3) {
printf("\n ending transaction");
} //End if for 3
if (iSelection != 1 || iSelection != 2 || iSelection != 3 ) {
printf("\nInvalid selection, please try again");
goto menu_options;
} //End if for Selection Error
答案 0 :(得分:0)
您的if
条件错误:
(iSelection != 1 || iSelection != 2 || iSelection != 3 )
当iSelection
不是1或者不是2或者不是3时,这将是真的。这将始终为真。您想要使用逻辑AND(&&
):
(iSelection != 1 && iSelection != 2 && iSelection != 3 )
此外,这不适合goto
。您最好使用while
循环:
while(1) {
printf("\n1\t To Make a Deposit Press One");
...
if (iSelection != 1 && iSelection != 2 && iSelection != 3 ) {
printf("\nInvalid selection, please try again");
} else {
break;
}
}
更好的是,使用switch
语句而不是多个if
块:
do {
printf("\n1\t To Make a Deposit Press One");
printf("\n2\t To Make a Withdrawal Press Two");
printf("\n3\t To End Transaction, Press Three\n");
scanf("%d", &iSelection);
int invalidSelection = 0;
switch (iSelection) {
case 1:
printf("\n Enter Amount to Deposit: ");
scanf("%f", &fTransAmount);
printf("\n Your new balance is: $%.2f", fBalance + fTransAmount);
break;
case 2:
printf("\n Enter Amount to Withdraw: ");
scanf("%f", &fTransAmount);
if (fTransAmount > fBalance)
printf("\n Insufficient funds, ending transaction.....\n");
else
printf("\n Your new balance is $%.2f\n", fBalance - fTransAmount);
break;
case 3:
printf("\n ending transaction");
break;
default:
printf("\nInvalid selection, please try again");
invalidSelection = 1;
break;
}
} while (invalidSelection);
答案 1 :(得分:0)
对于在失败时循环回到开头这么简单的事情,您应该使用while(1)
或for(;;)
循环无休止地重复,直到执行语句break
。它更具可读性,直接效果更好。在C中使用goto
主要用于资源清理,因为没有对象或异常,处理错误条件和释放内存可能很难。
所有人都说,你的问题是if (iSelection != 1 || iSelection != 2 || iSelection != 3 )
。您正在测试您的选择不是1
,还是2
还是3
。这始终是true
,因为它永远不会同时为三个。
您想:if (iSelection != 1 && iSelection != 2 && iSelection != 3 )
答案 2 :(得分:0)
你甚至不需要最终的if语句:
int repeat = 1;
while ( repeat) {
repeat = 0;
if (iSelection == 1) {
...
} else if ( iSelection == 2 ) {
...
} else if ( iSelection == 3 ) {
...
} else {
// print error here
repeat = 1;
}
}
或者你也可以使用switch-case结构。 这样做的好处是,如果你为iSelection添加了其他有效值,你只需要添加额外的"否则如果"块而不编辑最终的if语句。