做循环C编码错误

时间:2017-08-12 18:35:30

标签: c

这里出了什么问题?我收到错误Use of undeclared identifier 'answer'

这是我的代码:

        if (CalculatorChoice == 1) do {
            int a;
            int b;
            int sum;
            char answer;

            printf ("You have choosen addition, please enter first number: ");
            scanf("%d", &a);
            printf ("Now please enter second number to addit: ");
            scanf("%d", &b);
            printf("The sum is: %d \n\n", sum = a+b);

            printf("Do you want to go back to menupage? (y/n): ");
            answer = getchar();
            getchar();
        } while(answer=='y');

2 个答案:

答案 0 :(得分:0)

if (CalculatorChoice == 1)
  do {
    /* ... */
    char answer;

    /* ... */
  } while(answer=='y');

你已经在循环块中声明了变量answer ,但它是从while条件访问的,它是循环之外块。

您可以在循环体外移动声明来解决此问题:

if (CalculatorChoice == 1) {
  char answer;
  do {
    /* ... */
  } while(answer=='y');
}

答案 1 :(得分:0)

您的版本在块内声明了变量,无法在块中访问

此代码更改位置

if (CalculatorChoice == 1) 
{
  char answer;

  do {
    int a;
    int b;
    int sum;

    printf ("You have choosen addition, please enter first number: ");
    scanf("%d", &a);
    printf ("Now please enter second number to addit: ");
    scanf("%d", &b);
    printf("The sum is: %d \n\n", sum = a+b);

    printf("Do you want to go back to menupage? (y/n): ");
    answer = getchar();
    getchar();
    } while(answer=='y');
  }