【发布时间】:2023-03-16 15:09:01
【问题描述】:
我编写了这段代码来执行多个数学运算,用主菜单选择运算,然后重复它直到你想要并返回到主菜单。我已经使用 switch case 和 go-to 循环了它。我想替换 go-to,并希望得到有关如何在不使用 go-to 的情况下使其以相同方式运行的建议。 谢谢。
//I want the program of be infinite until you want to exit.Thus I used goto to continuously loop it back to either main menu or the mathematical operation you are in.
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int a,b,i,num,n;
char rep;
void main (void)
{
//main menu-(main:-for goto function)
main:
{
printf("\nMAIN MENU\n\n1. Factorial\n2. Sum\n3. Odd/Even\n4. Prime Number\n5. Multiplication\n6. Exit\n");
scanf("%d", &n);
}
switch (n)
{
case 1:
{
fact:
{
printf("Number- ");
scanf("%d", &num);
a=1;
for(i=1;i<=num;i++)
{
a=a*i;
continue;
}
printf("\nFactorial of %d= %d\n\n", num, a);
//This is how I loop it back to main menu or for repeating the mathematical operation using combination of conditional operators and goto.
printf("Repeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto fact;}):({goto main;});
}
}
case 2:
{
sum:
{
a=0;
printf("Value of repetitions- ");
scanf("%d", &num);
printf("Enter Digits to sum:\n");
for(i=1;i<=num;i++)
{
scanf("%d", &b);
printf("+ ");
a=a+b;
continue;
}
printf("\nThe Sum of Digits= %d\n\n", a);
printf("Repeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto sum;}):({goto main;});
}
}
case 3:
{
oe:
{
printf("Enter a Number- ");
scanf("%d", &a);
(a%2==0)?(printf("\n%d is an Even Number\n",a)):(printf("\n%d is an Odd number\n", a));
printf("\nRepeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto oe;}):({goto main;});
}
}
case 4:
{
prime:
{
printf("\nEnter a Number- ");
scanf("%d",&num);
if(num==2)
printf("\n\n%d is a Prime Number\n\n", num);
for(i=2;i<=num-1;i++)
{
(num%i==0)?({printf("\n\n%d is Not a Prime Number.\n\n", num);break;}):({printf("\n\n%d is a Prime Number\n\n", num);break;});
}
printf("\nRepeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto prime;}):({goto main;});
}
}
case 5:
{
mul:
{
a=1;
printf("Value of repetitions- ");
scanf("%d", &num);
printf("Enter Digits to multiply:\n");
for(i=1;i<=num;i++)
{
scanf("%d", &b);
printf("* ");
a=a*b;
continue;
}
printf("\nThe Multiplication of Digits= %d\n\n", a);
printf("Repeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto mul;}):({goto main;});
}
}
//Case 6 is only for aesthetic reasons.
case 6:
printf("\n\nPress Enter\n\n");
}
}
【问题讨论】:
-
这段代码根本无法编译。
(rep=='y')?({goto fact;}):({goto main;});是不正确的C,应该是if (rep == 'y') goto fact; else goto main;, -
我在 code:blocks 中多次使用它。至少喜欢10-20次。它顺利地遵守了。编译时报什么错误?
-
我想说,第一步是将执行单个工作(fact、sum、oe、prime、mul 等)的代码分解为单独的函数。然后,您可以更轻松地循环——在这些函数中,或者通过重复调用它们。无论哪种方式,
do{work();}while(!done());的一些变化将允许您根据用户的需要多次重复。 -
抱歉,这段代码有太多错误,根本无法挽救。不仅是 goto 问题,还要摆脱 continue、fflush(stdin)、void main、MS DOS 库、全局变量等。请采用一致的缩进样式,包含 2 或 4 个空格。总体而言,您需要一个新的学习来源 C。您当前的学习来源(老师/书籍)不可信,他们正在教您不良和不正确的习惯。
-
@Jabberwocky:你的编译器是一致的;该代码使用 GCC 扩展 — statement expressions,其中语法为
({ … })。
标签: c switch-statement goto