C语言 菜单驱动程序不起作用

ve7v8dk2  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(105)

我尝试用C创建一个菜单驱动程序,但完成一个功能后无法返回菜单。我如何编程,使程序要求用户继续或不后,每个功能和返回菜单?

//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语句还是其他语句。请发送帮助

e0bqpujr

e0bqpujr1#

如果你想从switch内部退出while(1)循环,最好使用循环控制变量:

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
}

相关问题