y / n循环在函数的末尾

时间:2017-10-16 19:19:57

标签: c macos

晚上好,

这是我的代码。我正在制作一个小计算器,但我正在努力争取使用y / n循环重复该函数。我看过别人,但似乎无法得到正确的答案。 谢谢。

#include <stdio.h>

int main()
{
  int n, num1, num2, result;
  char answer;
  {
    printf("\nWhat operation do you want to perform?\n");
    printf("Press 1 for addition.\n");
    printf("Press 2 for subtraction.\n");
    printf("Press 3 for multiplication.\n");
    printf("Press 4 for division.\n");
    scanf("%d", &n);
    printf("Please enter a number.\n");
    scanf("%d", &num1);
    printf("Please enter the second number.\n");
    scanf("%d", &num2);
    switch(n)
    {
      case 1: result = num1 + num2;
              printf("The addition of the two numbers is %d\n", result );
              break;
      case 2: result = num1 - num2;
              printf("The subtraction of the two numbers is %d\n", result );
              break;
      case 3: result = num1 * num2;
              printf("The multiplication of the two numbers is %d\n", result );
              break;
      case 4: result = num1 / num2;
              printf("The division of the two numbers is %d\n", result );
              break;
      default: printf("Wrong input!!!");
    }
    printf("\nDo you want to continue, y/n?\n");
    scanf("%c", &answer);
    while(answer == 'y');

  }
  return 0;
}

1 个答案:

答案 0 :(得分:3)

您有此代码

  char answer;
  {
    printf("\nWhat operation do you want to perform?\n");
    //...
    //... more code
    //...
    printf("\nDo you want to continue, y/n?\n");
    scanf("%c", &answer);
    while(answer == 'y');

  }

尝试将其更改为:

  char answer;
  do {
    printf("\nWhat operation do you want to perform?\n");
    //...
    //... more code
    //...
    printf("\nDo you want to continue, y/n?\n");
    scanf("%c", &answer);
  } while(answer == 'y');

所以基本形式是:

do {
    // code to repeat
} while (Boolean-expression);

BTW - 您应该始终检查scanf

返回的值

示例:

if (scanf("%c", &answer) != 1)
{
    // Add error handling
}

另请注意,您经常需要%c之前的空格来删除输入流中的任何空格(包括换行符)。像

if (scanf(" %c", &answer) != 1)
{
    // Add error handling
}