菜单驱动程序无法运行

问题描述 投票:0回答:1

我正在尝试在 C 中创建一个 Menu Driven 程序,但在完成一项功能后我无法返回菜单。我如何对其进行编程,以便程序在执行每个功能后询问用户是否继续并返回菜单?

//program of menu driven program
#include <stdio.h>
#include <stdlib.h>
int main() {
    int fac = 1, b, num, p, prime, click, out; //click for selecting the function and ext for goto
    while (1) {
        printf("Welcome to Varied Maths!");
        printf("\nYou can perform the following things here");
        printf("\n1.Factorial of a number\n2.Prime or not\n3.Odd or even\n4.Exit");
        printf("\nEnter your choice:");
        scanf("%d", &click);
        switch (click) {   //for seleting from menu
            case 1: //for factorial 
              printf("Factorial Calculator\n");
              printf("Enter the number:");
              scanf("%d", &num);
              for (p = 1; p <= num; p++) {
                fac = fac * p; //fac=1 which gets multiplied with the num entered the number gets increment and so on
                printf("Factorial of %d is %d", num, fac);
              }
              break;

            case 2: //prime numbers using for loop  
              //int prime,b,ent
              printf("Prime or not\n");
              printf("Enter the number:");
              scanf("%d", &prime);
              //int prime,b;
              if (num == 1) {
                printf("1 is Neither composite nor prime");
              }
              if (num == 0) {
                printf("Neithher compossite nor prime");
              }
              for (b = 2; b <= num - 1; b++)
                if (num % b == 0) {
                    printf("%d Not A prime", num);
                    break;
                }
              if (b == num) {
                printf("Prime Number");
              }
              break;
    
            case 3:
              int odd;
              printf("\nOdd or Even determiner");
              printf("\nEnter the number you want to know about:");
              scanf("%d", &odd);
              if (odd % 2 == 0) {
                printf("The entered number %d is a even number",odd);
              }
              if ((odd % 2) != 0) {
                printf("The entered number %d is a odd number",odd);
              }
              break;
    
            case 4:
              printf("\nThanks for Using Me.\nI would have been too happy if you checked out my functions ");
              break;
        }

        return 0;
    }
}

我该怎么办?我应该使用 continue 语句还是其他任何东西。请发送帮助

c menu return
1个回答
0
投票

如果您想从

while(1)
内部退出
switch
循环,最好是使用循环控制变量:

int end = 0;
while (!end) {
    switch(...) {
        case 4:
            end = 1;
            break;
    }
}

或者,如果你想使用

break
退出循环,你可以这样做:

while (1) {
    switch(...) {
        ...
    }
    if (click==4)
        break; // that break will exit the active control block, here the current while
}
© www.soinside.com 2019 - 2024. All rights reserved.