gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:45:44 25 4
gpt4 key购买 nike

所以我创建了一个简单的 for loopfor loop内。变量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;

}

最佳答案

尝试这个改变:

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

关于C: 为什么for循环中计数器没有重置为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39164965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com