将值赋值给for循环中更改的值

时间:2011-06-30 01:08:41

标签: c for-loop

在上一个问题中,我在某些代码中遇到问题,在显示之后,我在代码中遇到了其他问题:

i=1;
double smallest=diff[i][2];
int nxtcty;
for (j=2; j<=n; j++)
        {
          if (j!=i && diff[i][j]<smallest) {smallest=diff[i][j]; nxtcty=j;}
        }

值nxtcty没有变为j ..它输出一个奇怪的数字,我相信它是它的内存位置内容&gt;&gt; '134520820'......出了什么问题? 提前谢谢你......

EDIT 进一步调试,这里是完整的代码..它是一个非常初学的代码,用于计算几个城市之间的距离,给出它们的(x,y)坐标:

#include <stdio.h>
#include <math.h>

int main()
        {
          int i, j, n;
////////////// getting the number of cities ///////////////////
                printf("how many cities are there?\n");
                scanf("%d", &n); printf("so there is %d cities\n", n);
                int x[n];
                int y[n];
///////////// getting the x coordinates //////////////////////
                printf("enter their x coordinates, each followed by return\n");
                for (i=0; i<n; i++)
                        {
                          scanf("%d", &x[i]);
                          printf("the %dth city x coordinate is %d\n", i+1, x[i]);
                        }
///////////// getting the y cordinates /////////////////////
                printf("enter their y coordinates, each followed by return\n");
                for (i=0; i<n; i++)
                        {
                          scanf("%d", &y[i]);
                          printf("the %dth city y coordinate is %d\n", i+1, y[i]);
                        }
////////////// showing information ///////////////////////
                for (i=0; i<n; i++)
                        {
                          printf("city number %d is at (%d,%d)\n", i+1, x[i], y[i]);
                        }
//////////// get the distances /////////////////
double diff[n][n];
double h;
for (i=0; i<n; i++) {
        for (j=0; j<n; j++)
          {
                h=((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
                printf("city #%d distance %lf from city #%d\n\n", i+1, sqrt(h), j+1);
                diff[i][j]=sqrt(h);
          }
    }

for (i=0; i<n; i++) {for (j=0; j<n; j++)
{ printf("%lf  ", diff[i][j]);
if (j!=0 && n % (j+1)==0){printf("\n");}}
}
i=0;
double smallest=diff[i][1];
printf("smallest_initial   %lf \n",smallest);
int nxtcty=77;
printf("nxtcty_initial %d\n",nxtcty);
for (j=1; j<=n; j++)
        {
          printf("j_b4_if: %d,  smallest_b4_if:  %lf, nxtcty_b4_if:   %d\n",j, smallest, nxtcty);
          if ( diff[i][j]<smallest ) {smallest=diff[i][j]; nxtcty=j;
              printf("j_in_if: %d,  smallest_in_if:  %lf, nxtcty_in_if:   %d\n",j, smallest, nxtcty); }
printf("j_in_for: %d,  smallest_in_for:  %lf, nxtcty_in_for:   %d\n",j, smallest, nxtcty);
        }
printf("j %d,,  nxtcty %d\n", j, nxtcty);
                 return 0;
        }

2 个答案:

答案 0 :(得分:2)

你有没有打过将j的值分配给nxtcty的语句?如果没有,你看到的是nxtcty的初始(未初始化)值。

答案 1 :(得分:0)

如果将nxtcty初始化为2是个好主意,那么如果diff [i] [2]真的是最小的那么将是最小的索引,而不是仍未初始化。

如果您认为应该进行分配,请尝试每次循环打印出diff [i] [j]以进行检查。