C.中有三种情况的Switch语句.第三种情况运行不正常.下面的



是我编写的一个do-while循环。当我运行它时,前两个案例完成了它们的工作,运行得很完美。然而第三种情况应该退出程序,但它什么也不做,只是回到do-while循环开始时的一系列printf语句。关于我做错了什么,有什么建议吗?

do
{
    printf("Choose one of the following (1, 2, or 3) n");
    printf("1. Find GCD of two positive integersn");
    printf("2. Sort 3 integers in the ascending ordern");
    printf("3. Quit the programn");
    printf("Please enter your choice: ");
    scanf("%d", &option);
    switch (option)
    {
        case 1:
            gcd(p, q);
            printf("nDo you want to try again? Say Y(es) or N(o): ");
            getchar();
            response = getchar();
            break;
        case 2:
            sort(p, q, r);
            printf("nDo you want to try again? Say Y(es) or N(o): ");
            getchar();
            response = getchar();
            break;  
        case 3:
            break;
    }
}
while (response == 'Y' || response == 'y'); //Condition that will determine whether or not the loop continues to run.
printf("nThank you for using my progam. Goodbye!nn");
return 0;
} 

响应变量保持Y或Y,while循环从不退出。

添加

response = 'x'; //or something that isn't Y or y

课间休息前;在情况3中:选项。

break语句从第一个迭代循环中退出。在您的情况下,这是switch

您必须修改响应(例如response=0)。

    case 3:
        response=0; //different than 'Y' or 'y'
        break;

这样做:

case 3:
  return 0;

你也可以考虑消除情况3,然后这样做:

default:
  return 0;

在情况3中,没有来自用户的输入,因此响应变量保持为true,请尝试向用户请求输入,或者只输入response='(任何会使条件为false的字母)'

break语句不会退出程序,它只是从switch块中退出
要退出:
1.#include<stdlib.h>
使用exit(0);而不是break语句
2.将case 3更改如下:
response='N';break;

案例3中的break语句只是从案例3中退出,而不是从程序中退出。如果您想在情况3中退出程序,请使用return语句。

返回0;

此语句存在于程序中,而不是重复while循环。

您只需中断开关情况。

如何使用:

  case 3:
      return;
      break;

最新更新