如何在if语句之后跳回代码顶部C语言
我试图让我的程序在用户从菜单中选择一个选项后重新启动。 当用户选择1,然后输入捐赠金额时,我希望程序再次启动,并显示菜单您想做什么?而不仅仅是重新启动if语句 我是否应该在if语句中添加一个for循环来实现这一点?谢谢你的帮助如何在if语句之后跳回代码顶部C语言,c,for-loop,if-statement,C,For Loop,If Statement,我试图让我的程序在用户从菜单中选择一个选项后重新启动。 当用户选择1,然后输入捐赠金额时,我希望程序再次启动,并显示菜单您想做什么?而不仅仅是重新启动if语句 我是否应该在if语句中添加一个for循环来实现这一点?谢谢你的帮助 printf("What would you like to do?\n"); printf(" 1 - Donate\n"); printf(" 2 - Invest\n"); printf(" 3 - Print
printf("What would you like to do?\n");
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if(menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
}
当用户选择1,然后输入捐赠金额时,我希望程序再次启动并显示菜单
照办
for(;;) {
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if(menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
// NO BREAK
}
else {
.... management of other cases
break;
}
}
或者如果你愿意的话
do {
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if(menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
}
// ... management of other cases
} while (menu_option==1);
但是您确定不想在案例2和案例3中重做吗?在这种情况下,当菜单_选项==1时替换;按while菜单_选项!=4.或者在第一个方案中,仅当菜单选项为4时才中断
我还建议您检查scanf%d的返回值,&menu\u选项;为了确保输入中给出了一个有效的整数,并且设置了菜单_选项将所有内容放入一个for;;{并执行一次中断;在除case1之外的所有情况下退出循环,将其放入循环中。
#include <stdio.h>
int main()
{
int menu_option;
double donation;
int donations_made = 0;
int current_Balance = 0;
int initial_Balance = 0;
for (;;)
{
printf("What would you like to do?\n");
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if (menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
}
else if (menu_option == 4)
break;
}
}