0

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

do
{
    printf("Choose one of the following (1, 2, or 3) \n");
    printf("1. Find GCD of two positive integers\n");
    printf("2. Sort 3 integers in the ascending order\n");
    printf("3. Quit the program\n");
    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!\n\n");
return 0;
} 
4

7 回答 7

2

响应变量保持 Y 或 y 并且 while 循环永远不会退出。

添加

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

休息前;情况 3:选项。

于 2013-02-15T14:43:57.490 回答
2

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

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

    case 3:
        response=0; //different than 'Y' or 'y'
        break;
于 2013-02-15T14:44:36.230 回答
1

像这样做:

case 3:
  return 0;

您也可以考虑消除案例 3 并执行以下操作:

default:
  return 0;
于 2013-02-15T14:50:40.403 回答
0

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

返回0;

该语句存在程序而不是重复while循环。

于 2013-02-15T15:38:48.687 回答
0

在第 3 种情况下,没有来自用户的输入,因此响应变量保持为真,请尝试向用户询问输入或只输入 response = '(任何会使条件为假的字母)'

于 2013-02-15T14:51:28.353 回答
0

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

于 2013-02-15T14:51:33.513 回答
0

您只需中断开关盒即可。

如何使用:

  case 3:
      return;
      break;
于 2013-02-15T14:45:24.210 回答