C:为什么在for循环中计数器没有重置为0

C:为什么在for循环中计数器没有重置为0,c,for-loop,counter,C,For Loop,Counter,所以我在for循环中创建了一个简单的for循环。var FrequecCount未重置为0,不理解原因 我已经讨论了数组x和hist数组,需要一个计数器变量来计算x中与hist位置相同的值的频率 #include <stdio.h> void create_hist(double *x, int count, int *hist) { int frequencyCount = 0; for (int iHist = 0; iHist <= 5; iHist

所以我在for循环中创建了一个简单的for循环。var FrequecCount未重置为0,不理解原因

我已经讨论了数组x和hist数组,需要一个计数器变量来计算x中与hist位置相同的值的频率

#include <stdio.h>

 void  create_hist(double *x, int count, int *hist) {
    int frequencyCount = 0;
    for (int iHist = 0; iHist <= 5; iHist++) {
        //initalize to zero
        hist[iHist] = 0;

        for (int ix = 0; ix < count; ix++) {
            // convert to int
            x[ix] = (int)x[ix];

            if (x[ix] == hist[iHist]) {
                frequencyCount++;
            }
        }
        // add to the hist[] array the frequency count at position i
        hist[iHist] = frequencyCount;
        frequencyCount = 0;
    }

    int main( void ) {
    double x[5] = {0, 0, 0, 0, 3};
    int hist[5];
    int count = 5; 

    create_hist(x, count, hist);

    printf( "\tInput data:\n" );
    for ( int i = 0; i < count; i++ ) {
        printf( "\t%d\t%f\n", i, x[i] );
    }

    printf( "\tHistogram:\n" );
    for ( int i = 0; i <= 5; i++ ) {
        printf( "\t%d\t%d\n", i, hist[i] );
    }

    return 0;

}
尝试以下更改:

for (int iHist = 0; iHist < 5; iHist++) {  // <= changed to <
    int frequencyCount = 0;                // Moved this line to be inside the loop
frequencyCount变量正在重置。还有另一个原因,你的输出不是你所期望的

此if语句很可能是错误的:

    if (x[ix] == hist[iHist]) {
        frequencyCount++;
    }
在此阶段,hist[iHist]始终为0,这是您在循环之前分配的值

我想你的意思是:

    if (x[ix] == iHist) {
        frequencyCount++;
    }

您还需要更改我尝试过的循环范围条件。我尝试将计数器设置为0,测试for循环是否正常工作,没有成功!你为什么要这样写代码?在外部循环内声明frequencyCount。而不是在外部范围中声明它,因为您将只在循环中使用它。但是你说的话没有道理。另外,请显示hist和x的声明/定义。x[ix]=intx[ix];什么。嘿,我添加了主函数,这样你就可以看到声明了。请让我知道,如果你有任何想法是什么问题的回路控制iHist
    Input data:
    0       0.000000
    1       0.000000
    2       0.000000
    3       0.000000
    4       3.000000
    Histogram:
    0       4
    1       0
    2       0
    3       1
    4       0