in a previous question i had a problem in some code,, after revealed, i had other problem in the code:
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;}
}
the value nxtcty is not changing to j.. it outputs a strange number which i believe it is the memory location content for it >> '134520820'.. what went wrong?? thank you in advance...
EDIT for further debugging, here the full code.. it is a very beginner code to calculate distance between several cities with their (x,y) coordinates given:
#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;
}
Do you ever hit the statement that assigns the value of j to nxtcty? If not, what you see is the initial (uninitialized) value of nxtcty.
If would be a good idea to initialise nxtcty to 2 so that if diff[i][2] really is the smallest then will be the index of the smallest and not still uninitialised.
If you think that an assignment should be taking place, try printing out diff[i][j] each time round the loop to check.
精彩评论