【发布时间】: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。而不是在外部范围内声明它,因为您只会在循环内使用它。但是你说的没有意义。另外,请显示hist和x的声明/定义。 -
x[ix] = (int)x[ix];什么。 -
嘿,我已经添加了 main 函数,这样你就可以看到声明了。如果您知道问题出在哪里,请告诉我
-
循环控制
iHist <= 5;破坏了数组int hist[5];所以在函数中,hist[iHist] = 0;是未定义的行为,之后任何事情都可能发生。