【问题标题】:C: Why is counter not resetting to 0 in for loop [closed]C:为什么在for循环中计数器没有重置为0[关闭]
【发布时间】:2017-01-03 01:08:49
【问题描述】:

所以我在for loop 中创建了一个简单的for loop。 var frequecyCount 没有重置为 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;

}

【问题讨论】:

  • 试过了。我尝试将计数器设置为 0,测试 for 循环是否正常工作,没有成功!
  • 你为什么要这样写代码?在外循环内声明frequencyCount。而不是在外部范围内声明它,因为您只会在循环内使用它。但是你说的没有意义。另外,请显示histx 的声明/定义。
  • x[ix] = (int)x[ix]; 什么。
  • 嘿,我已经添加了 main 函数,这样你就可以看到声明了。如果您知道问题出在哪里,请告诉我
  • 循环控制iHist &lt;= 5; 破坏了数组int hist[5]; 所以在函数中,hist[iHist] = 0;未定义的行为,之后任何事情都可能发生。

标签: c for-loop counter


【解决方案1】:

frequencyCount 变量正在重置。您的输出不是您所期望的还有另一个原因。

这个if 声明很可能是错误的:

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

在这个阶段,hist[iHist] 始终是0(这是您在循环之前分配的值)。

我想你的意思是:

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

您还需要将循环范围条件从i &lt;= 5 中的i &lt;= 5 更改为i &lt; 5,并将create_hist 中的iHist &lt;= 5 更改为iHist &lt; 5,以避免缓冲区溢出。

进行这些更改会导致输出:

    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

【讨论】:

    【解决方案2】:

    试试这个改变:

    for (int iHist = 0; iHist < 5; iHist++) {  // <= changed to <
        int frequencyCount = 0;                // Moved this line to be inside the loop
    

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 2019-03-14
      • 2023-04-03
      • 2020-11-26
      相关资源
      最近更新 更多