我在行中收到未声明的标识符错误:“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/