在C中提前终止的简单while循环问题

时间:2014-11-26 15:16:18

标签: c while-loop

我有以下代码:

    //get distances
int a = -1;
int b = -1;
while ((a != 0) && (b != 0)) {
    scanf("%d %d", &a, &b);
    printf("The shortest path from %d to %d is %.1lf meters.\n", a, b, D[a][b]);
}

循环似乎在一次输入后终止,尽管事实上a和b没有被输入为0。

即:

0 2
The shortest path from 0 to 2 is 237.7 meters.

不确定为什么会这样做所以任何帮助都会受到赞赏。

然后终止

需要时的完整代码

#include <stdio.h>
#include <stdlib.h>
#define INF 41e6

double** new2Ddouble(int n, int m);
void free2D(double **a);

int main() {
    //get # of nodes
    int size = 0;
    scanf("%d", &size);

    //create matrix
    double **D = new2Ddouble(size, size);

    //fill with inf for D[i][j]
    int i;
    int j;
    for(i=0; i<size; i++) {
        for(j=0; j<size;j++){
            D[i][j] = INF;
        }
    }

    //fill D[i][i] with INF
    for(i=0;i<size;i++) D[i][i] = INF;

    int exit = 0;
    int I;
    int J;
    double d;
    while(exit != 1) {
        //populate values in matrix
        scanf("%d %d %lf", &I, &J, &d);
        if(I == 0 && J == 0 && d == 0){
            //we can exit
            exit = 1;
        } else {
            D[I][J] = d;
        }
    }

    //calculate distances
    /* Floyd-Warshall Algorithm */
    int k;
    for (k=0; k<size; ++k)
        for (i=0; i<size; ++i)
            for (j=0; j<size; ++j)
                if (D[i][k]+D[k][j] < D[i][j])
                    D[i][j] = D[i][k]+D[k][j];

    exit = 0;
    //get distances
    int a = -1;
    int b = -1;
    while ((a != 0) && (b != 0)) {
        scanf("%d %d", &a, &b);
        printf("The shortest path from %d to %d is %.1lf meters.\n", a, b, D[a][b]);
    }
    return 0;
}


double** new2Ddouble(int n, int m) {
    int i;
    double **ret = (double**) malloc(n*sizeof(double*));
    double *a = (double*) malloc(n*m*sizeof(double));
    for (i=0; i<n; ++i) ret[i] = &a[i*m];
    return ret;
}

void free2D(double **a) { free(a[0]); free(a); }

3 个答案:

答案 0 :(得分:1)

scanf("%d %d", &a, &b);

在此行中,您分别扫描ab 0和2的值。 因此,一旦将新值扫描到这些变量,那么您的while条件将失败,因为您已显示a0,并且永远不会检查第二个条件,因为0 && (0|1) = 0

一旦a=0条件失败并退出循环。

答案 1 :(得分:0)

while ((a != 0) && (b != 0))

此循环将在a b为零时终止,并在a b时继续不是零。您输入a为0,并且条件a!=0失败,您的循环终止。

答案 2 :(得分:0)

there are a couple of problems with this line:

scanf("%d %d", &a, &b);

Note: scanf does not automatically consume white space, 
   so on the second iteration
   the next input char is a newline.
   so scanf fails
Note: all I/O statements 
   should have the returned value checked
   to assure success of the operation

to fix those items, write it like so:

if( 2 != scanf(" %d %d", &a, &b) )
{
    perror( "scanf failed" );
    exit( EXIT_FAILURE );
}

the leading ' ' in the format string causes leading 
white space, like the newline, to be consumed
the 'if' checks the returned value from
scanf to assure that all the input conversions were successful