繁体   English   中英

在c中使用未声明的标识符

[英]Use of undeclared identifier in c

我在行中收到未声明的标识符错误:“ printf(”%f“,new_u [i]);” 这很奇怪,因为我可以在for循环中以值打印i。 为什么会出现该错误?

const int MAX = 101;

int main(void) {

    int t = 1; //time
    int m = 0; //number of segments of bar
    int n = 0; //number of time intervals

    double new_u[MAX]; //to store temps currently being converted (array of 101 doubles)
    double old_u[MAX]; //to store temps corresponding to prev time (array of 101 doubles)

    printf("Enter number of segments: ");
    scanf("%d", &m);
    printf("Enter number of time intervals: ");
    scanf("%d", &n);

    double h = (1.0/m); //length of bar segments
    double d = (1.0/n); //length of time interval

    for (int j = 1; j <= n; j++) { //j is which time interval the iteration is on
        int t_j = j * d; //t_j is the actual fraction of a second the iteration is on (i.e. 0.0, 0.2, 0.4...)
        new_u[0] = new_u[m] = 0.0;
        for (int i = 1; i < m; i++)
            new_u[i] = old_u[i] + d/(h*h)*(old_u[i-1] - 2*old_u[i] + old_u[i+1]);
        printf("%f", new_u[i]);
        //I need to finish code by printing new_u values
        //Then copy new_u into old_u for next pass;
    }

}

由于内部for循环未使用任何花括号,因此该printf语句不知道i的值 。在条件和循环语句中,如果没有为其创建花括号(或创建的块),则它们只能进行操作并且范围仅限于声明之后的声明。

for (int i = 1; i < m; i++)
        new_u[i] = old_u[i] + d/(h*h)*(old_u[i-1] - 2*old_u[i] + old_u[i+1]); //i  is known here
        printf("%f", new_u[i]); //i is not available for this

用这样的括号

 for (int i = 1; i < m; i++)
 {
    new_u[i] = old_u[i] + d/(h*h)*(old_u[i-1] - 2*old_u[i] + old_u[i+1]);
    printf("%f", new_u[i]);
 }

未知标识符是i ,不是new_u 您需要大括号:

for (int i = 1; i < m; i++) {
    new_u[i] = old_u[i] + d/(h*h)*(old_u[i-1] 
               - 2*old_u[i] + old_u[i+1]);
    if (i>1) putchar(' ');
    printf("%f", new_u[i]);
}

在错误的代码版本中, i只能通过分配给new_u[i]才能new_u[i] ,而您的printf不到

顺便说一句,您可能希望在数字之间放置一个空格,就像我对putchar所做的那样。 否则,输出可能无法读取,例如,两个数字1.233.45 1.233.45

由于您有一个for (int i=1;循环,所以i的范围仅是for的(测试,增量和)主体;在您的情况下,该主体是单个分配。

只需在括号中放一个括号即可覆盖打印功能...

for (int i = 1; i < m; i++)
 {
    new_u[i] = old_u[i] + d/(h*h)*(old_u[i-1] - 2*old_u[i] + old_u[i+1]);
    printf("%f", new_u[i]);
 }

对以上评论的回答是

1)。 “ i”是一个未知的标识符,因为它现在超出了范围,因为它仅具有第二个FOR循环的范围。

2)。 'i'具有值,因为您将值放入FOR循环中,并且超出范围后,自动变量也不会被销毁,它会一直保留在那里,直到执行时被某些新变量覆盖为止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM