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

标签 c undeclared-identifier

我在行中收到未声明的标识符错误:“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 循环中使用任何大括号,所以 i 的值对于 printf 语句 是未知的。在条件语句和循环语句中,如果没有大括号(或创建的 block )用于它们,那么它们只能操作并且范围仅限于声明之后的语句。

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]);
 }

关于c - 在 c 中使用未声明的标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25757360/

相关文章:

c - 使用 qsort() 对整数数组进行排序并交换字符串

c - Malloc 有 C 字符串垃圾?

c++ - 从函数 C++/SFML 加载资源时出现问题

c++ - 稍后在程序中使用在 if else 构造内声明的变量会导致未声明的标识符错误

c++ - 如何使用GLOBAL变量并使其在不同函数中使用?

c指针数组段错误

c - 追加到 C 数组时出现总线错误

c - tar_append_tree 上的 libtar 段错误

在另一个成员函数中使用时,C++ 成员函数错误 "Undeclared Identifier"

C++ 类实例标识符未声明