gpt4 book ai didi

c - C语言循环过程中数组元素的值会自行改变

转载 作者:行者123 更新时间:2023-11-30 19:33:24 26 4
gpt4 key购买 nike

我用C编写了一些简单的代码。问题是元素值在循环期间发生变化,即使没有这样的命令。循环结束后,第一次循环中计算的所有元素都变为零。但是在第二个或更高编号的循环中计算的元素显示正确的值,它们不会变为零(显然)。那么为什么这些元素会变为零呢?哪里错了?

我每次都打印了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;
}

最佳答案

如果我理解你的问题x[0]y[0]为零,所有其他索引都正常。所以在你的代码中,存在一些错误。1.for ( j=0; j<=Ny; j++ )for ( i=0; i<=Nx; i++ )如果您正在访问未为您的程序分配的内存并且可能是只读的,则可能会收到错误 SEGFAULT。2.x[i]=(double)i/(Nx+1)*lengthX;当 j 和 i 初始化为零时,您开始计算,这就是为什么您在第一个索引处得到零的原因。

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

关于c - C语言循环过程中数组元素的值会自行改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45780132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com