gpt4 book ai didi

c - switch 语句即使在 break 之后也执行 case 2

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:17 25 4
gpt4 key购买 nike

当情况 1 时,程序会执行预期的代码,但当它询问您是否要再次计算体积时,如果您选择是,它只会执行情况 2。我不确定哪里出了问题。除非您在菜单中选择 2,否则如何让它只执行情况 1?

        #include <stdio.h>
#include <stdlib.h>

int main()
{
float menu1, opt1, opt2, opt3, opt4, t;
int td;

printf("Enter: ");
scanf("%d",&td);
switch(td) {
case 1:
printf("Enter a, b, c, and h of the triangular prism in meters\n\n");
printf("a ");
scanf("%f", &opt1);
printf("b ");
scanf("%f", &opt2);
printf("c ");
scanf("%f", &opt3);
printf("h ");
scanf("%f", &opt4);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}

case 2:
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
scanf("%f", &opt1);
printf("h ");
scanf("%f", &opt2);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
}
}

最佳答案

您的 break 语句 [for case 1:] if block 中。如果 if 都不是 true,那么您就失败了。

这是你的原作:

case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
// BUG: there should be a break here

case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...

固定代码如下:

case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
break; // FIX: this is your _missing_ break statement

case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...

关于c - switch 语句即使在 break 之后也执行 case 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36683296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com