为什么for循环不适用于特定值?

时间:2017-07-27 13:53:28

标签: c

int main()
{   
    FILE *wg = NULL;  
    wg = fopen("wangdata.txt","w");
    if(wg == NULL)
    {
         printf("Error in opening file wg!\n");
    }

    int vertices = 100, edges = 400, i; // 20,50:(100,50)
    int strings = 160;
    int v1, v2,j;
    double t=0.0;
    double dt=0.1;
    double b[strings];
    double x[vertices], x1[vertices];
    double x2[vertices];
    unifRand(x,x1,x2);

    struct Edge * adjacencyList[vertices + 1];
    // Size is made (vertices + 1) to use the
    // array as 1-indexed, for simplicity

    // initialize array:
    for (i = 0; i <= vertices; ++i) {
        adjacencyList[i] = NULL;
    }

    for (i = 0; i <= edges; ++i) {
        //scanf(%d%d", &v1, &v2);
        v1 = rand()%100;
        v2 = rand()%100; 

        // Adding edge v1 --> v2
        // Add edge from v1 --> v2
        if(v1 != v2)
        adjacencyList[v1] = addEdge(adjacencyList[v1], v2);

        // Adding edge v2 --> v1
        // Remove this if you want a Directed Graph
        adjacencyList[v2] = addEdge(adjacencyList[v2], v1);
    }

    // Printing Adjacency List
    printf("\nAdjacency List -\n\n");
    for(j=0; j<strings; j++){

       for (i = 0; i <= vertices; ++i) {
            printf("adjacencyList[%d] -> ", i);
            struct Edge * traverse = adjacencyList[i];
            while (traverse != NULL)
            {
              b[j] = j/vertices;
              fprintf(wg,"%d %d \t\t%0.3lf\t\t\t%0.1lf\t%0.6lf\t\n", i, traverse->vertex, (-log(1-x[i])*(traverse->vertex)),b[j],x[i]);
              printf("%d -> ", traverse->vertex);
              traverse = traverse->next;
            }
            printf("NULL\n");
       }
     }

   return 0;
   fclose(wg);
   wg = NULL;
}

主函数中的上述for循环仅在输出文件中为0打印1b[j]。在打印j时,它会打印j的所有值,但该循环不适用于b[j]。我不知道哪里出错了?我将b[j]定义为由总顶点标准化的字符串数(图论语言中的网络大小)。

2 个答案:

答案 0 :(得分:1)

您要将int除以int。它将产生int值。由于j始终低于vertices,因此您将获得0

尝试

b[j] = (double)j/(double)vertices;

答案 1 :(得分:1)

j从0到159并除以100.由于整数除法向零舍入,因此得到0或1。

如果您想要一个非舍入的double结果,请在分割前将一个或两个数字转换为double

b[j] = j / (double) vertices;