在c语言中,数组元素的值在循环过程中会自动改变
我已经用C编写了一些简单的代码。问题是元素值在循环过程中不断变化,即使没有这样的命令。在第一个循环中计算的所有元素在循环结束后变为零。但在第二个或更高编号的循环中计算的元素显示正确的值,它们不会变为零(显然)。那么为什么这些元素变为零呢?错在哪里 我每次都打印在c语言中,数组元素的值在循环过程中会自动改变,c,arrays,loops,for-loop,nested-loops,C,Arrays,Loops,For Loop,Nested Loops,我已经用C编写了一些简单的代码。问题是元素值在循环过程中不断变化,即使没有这样的命令。在第一个循环中计算的所有元素在循环结束后变为零。但在第二个或更高编号的循环中计算的元素显示正确的值,它们不会变为零(显然)。那么为什么这些元素变为零呢?错在哪里 我每次都打印u(1,0)的值 #include <stdio.h> /* Standard Library of Input and Output */ #include <complex.h> /* Stand
u(1,0)
的值
#include <stdio.h> /* Standard Library of Input and Output */
#include <complex.h> /* Standard Library of Complex Numbers */
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define pi 3.141592
int main() {
// Declaration variables
// Integers
int N = 2, Nx = N, Ny = N, i, j; // IMPORTANT GIVE N-1 FOR N
double x[Nx], y[Ny], lengthX = 1.0, lengthY = 1.0;
double complex u[Nx][Ny];
// FOR X DIRECTION
for (i = 0; i <= Nx; i++) {
x[i] = (double)i / (Nx + 1) * lengthX;
//printf("x coordi is %.15f \n", x[i]);
}
// FOR Y DIRECTION
for (j = 0; j <= Ny; j++) {
y[j] = (double)j / (Ny + 1) * lengthY;
//printf("x coordi is %.15f \n", x[i]);
}
for (j = 0; j <= Ny; j++) {
for (i = 0; i <= Nx; i++) {
printf("x coordi is %.15f \n", x[i]);
u[i][j] = sin(2.0 * pi * x[i]) * cos(2.0 * pi * y[j]);
// x[i] = (double)i / (Nx + 1) * lengthX;
printf("u is (i,j) = (%i,%i)\t%.15f\t%f\t%f\n", i, j, u[i][j], x[i], y[j]); //correct
printf("u is (i,j) = (%i,%i)\t element u[1][0] is %.15f \n\n\n", i, j, u[1][0]);
}
printf("\n\n\n End of inside loop (i,j)=(%i,%i) u(1,0) is \t%.15f \n", i, j, u[1][0]);
}
printf("\n\n u is %i\t%i\t%.15f \n\n", i, j, u[1][0]);
printf("\n\n\n\n Why u(1,0) value become zero in the last loop ???????\n");
printf("\n\n\n\n Not only u(1,0) value become zero, but all u(:,0) in the last loop became zero !\n");
//
return 0;
}
#包含/*标准输入输出库*/
#include/*复数标准库*/
#包括
#包括
#包括
#定义pi 3.141592
int main(){
//声明变量
//整数
int N=2,Nx=N,Ny=N,i,j;//重要的是给N取N-1
双x[Nx],y[Ny],长x=1.0,长x=1.0;
双复u[Nx][Ny];
//对于X方向
(i=0;i如果我理解你的问题,x[0]
和y[0]
是零,所有其他索引都可以。因此,在你的代码中,有一些bug。
1.for(j=0;j数组超出其范围。正如在地板上一样,您应该更正循环:
替换(i=0;ii=0;ii=0;ii=0;ifor(j=0;jMANY非常感谢Jean-François Fabre和Weather vane这一切都是因为我用FORTRAN编写代码!感谢您的简要解释。谢谢
for ( i=1; i<=Nx; i++ ) {
x[i-1]=(double)i/(Nx+1)*lengthX;
//printf("x coordi is %.15f \n", x[i]);
}
// FOR Y DIRECTION
for ( j=1; j<=Ny; j++ )
{
y[j-1]=(double)j/(Ny+1)*lengthY;
//printf("x coordi is %.15f \n", x[i]);
}