首页 > 解决方案 > 即使我在顶部写了 char 答案,为什么我仍然第一次使用此函数错误?

问题描述

我尝试了我发现的每一个解决方案来解决这个问题,但没有帮助我。我也试过不做,while (true)但也做不到。我的错误:

error: ‘answer’ undeclared (first use in this function)
   30 |  }while (answer == 'n' || answer == 'N');
      |          ^~~~~~

.

#include <stdio.h>
int main ()
{
        do {
        double length;
        char unit;
        char answer;
        printf("Enter the length: ");
        scanf("%lf%c", &length, &unit);
        if (unit == 'i' || unit == 'I')
        {
                printf("%1.2lf i = %lf c \n", length, 2.54*length);
        }
        else if (unit == 'm' || unit == 'M')
        {
                printf("%1.2lf i = %lf c \n", 39.3701*length, 100*length);
        }
        else if (unit == 'c' || unit == 'C')
        {
                printf("%1.2lf i = %lf c \n", length/2.54, length);
        }
        else
        {
                printf("0 i = 0 c");
        }

        printf("Do you want to start over? y/n \n");
        scanf("%c", & answer);
        answer = getchar();
        }while (answer == 'n' || answer == 'N');

        return 1;
}

标签: cwhile-loopdo-while

解决方案


char answer;位于do { ... } while();循环内,范围仅限于大括号内。因此,您无法answerwhile()有条件的情况下访问。它在大括号之外。


推荐阅读