c - C中重复某个菜单的函数

标签 c function

我是 C 编程语言的新手。我希望以下代码在“交易成功”后重复主菜单,并在输入金额后存储新余额。我该怎么做。这是代码

#include<stdio.h>
int main()
{
    int mainmenu, amt, balance = 0;
    printf("1.Pay \n");
    printf("2.Balance \n");
    printf("3.Transaction history \n");
    scanf("%d",&mainmenu);

    if(mainmenu == 1){
        printf("Select Amount \n");
        printf("$0.50 \n");
        printf("$1.00 \n");
        printf("$1.50 \n");
        printf("$2.00 \n");
        scanf("%d",&amt);

        if(amt == 1){
            balance = balance + 0.5;
            printf("Transaction Successful \n");

        }
        if(amt == 2){
             balance = balance + 1;
            printf("Transaction Successful \n");
        }
        if(amt == 3){
             balance = balance + 1.5;
            printf("Transaction Successful \n");
        }
        if(amt == 4){
             balance = balance + 2;
            printf("Transaction Successful \n");
        }

    }
    if(mainmenu == 2){
        printf("\n");
        printf("Balance = %d",balance,"\n");
    }
    if(mainmenu == 3){
        printf("No Transaction History At The Moment");
    }

}

最佳答案

在这种情况下,最简单的方法可能就是使用 while 循环。

while(1){
  //mainmenu here
  printf("4. Exit Program");
  scanf("%d", &mainmenu);

  //if statements/functions here
}

这将要求您添加第四个选项以退出 while 循环,因此它不会无休止地运行(您也可以使用其他方法来知道何时退出)。一个好的方面是,如果他们不小心输入了一些无效的东西,例如 5 或 7,它不会导致任何错误,而只是再次运行循环。

请记住,您必须将所有 if 语句放在 while 循环中,或者将它们放在不同的函数中并在获得用户输入后调用该函数。

附言不相关但 switch 语句可能比这里的 if else 语句更容易一些。它们不是必需的,但可以让您的生活更轻松一些。

关于c - C中重复某个菜单的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833835/

相关文章:

c++ - 如何从此源代码中删除所有空格字符

javascript - 需要使用javascript在文本框中显示加法结果

c++ - 是否在 C++ 中使用 double() 函数?

javascript - 将图像源复制到另一个图像标记多个具有单一功能的实例?

c - 实现循环队列的细微错误

c - float 字到字符串的宽度和精度格式

c - 如何 malloc 结构数组

c - 如何在 c 中指定 64 位整数

c - 试图找到两点之间的距离,但我得到了错误的答案 :(

function - 与 OCaml 中的函数匹配?