繁体   English   中英

为什么这种C数组算法在第二次迭代中失败?

[英]Why is this C Array algorithm failing on the second iteration?

我在checkTotal()函数时遇到麻烦。 在第一次迭代中,它可以正确地对所有具有其值的值求和。

但是,在我的第二次迭代中,加起来的值并不准确,我不确定这些数字是从哪里来的。

 int checkTotal(int numSchemes, int numComponents, int weight[numComponents][numSchemes], char **list){
     int cCounter = 0;
     int total = 0;
     while (cCounter < numComponents){
        total = total + weight[numSchemes][cCounter];
        printf("%d\n", total);
        cCounter++;
     }

     return total;
}

这是调用checkTotal的函数

void weightInput(int numSchemes, int numComponents, int weight[numComponents][numSchemes], char **list){
    int sCounter = 0;
    int cCounter = 0;

            // iterating through the number of schemes
    while (sCounter < numSchemes){
        printf("\nMarking scheme #%d: \n", (sCounter+1));
        while (cCounter < numComponents){
            printf("\tenter %s's weight:  ", list[cCounter]);
            int theWeight;
            scanf("%d", &theWeight);
            weight[sCounter][cCounter] = theWeight;
            cCounter++; 
        }   
        //printf("%d\n", weight[sCounter][cCounter]);
        printf("THE TOTAL IS %d\n", checkTotal(sCounter, numComponents, weight, list));
        sCounter++;
        cCounter = 0;
    }
 }

该函数采用2d数组,遍历第二维,然后将所有int相加以得到总计。

它成功地求和并在第一次迭代中返回总和,但是对于我的第二次迭代,它现在进行了。

如果我为第一次迭代输入33、22、5、5,它将返回65。

对于我的第二次迭代,我将有(10,5,10,25),但是当它应该为50时,它将返回47。

如果有人可以提供帮助,将不胜感激。 先感谢您,

在我看来,逻辑可能会重新出现? 你有

int weight[numComponents][numSchemes]

在签名行中,然后使用进行访问。

weight[numSchemes][cCounter]

cCounter和numSchemes应该相反吗?

total = total + weight[numSchemes][cCounter];

应该:

total = total + weight[numComponents][cCounter]; 

谢谢@ user3629249

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM