我想保持用户指定数字的运行平均值。我正在使用新的和旧的使用模数运算符环绕数组。我想用模运算符来做到这一点。但每次我为 N 输入 10 时,我似乎无法再次在第一个索引处输入值。
int main (int argc, char *argv[]){
int DATA[M]={'\0'}, N, new=0, old=0, i, values=0;
float total, average;
printf("Enter the number of values to be averaged over (N): ");
scanf("%d", &N);
assert(N > 0 && N <= 10);
while(1){
printf("Enter a value: ");
scanf("%d",&DATA[new]);
printf("Buffer contents: ");
for(i=0;i<M;i++)
printf("%d\t",DATA[i]);
printf("\n");
if(values <= N-1){
total += DATA[values];values++;
average = total/values;
printf("Number of values entered: %d\t\tAverage over: %d\t\t\tAverage: %.2f\n", values, values, average);
}
else {
values++;total-=DATA[old];
old++;total+=DATA[new];
average = (total/N);
printf("Number of values entered: %d\t\tAverage over: %d\t\t\tAverage: %.2f\n", values, N, average);
}
new++;
new%=(M);old%=(M);
printf("\n");
}
return(0);
}
最佳答案
total += DATA[values];values++;
total
从未初始化,因此使用未初始化的变量会导致未定义的行为。
关于c - 使用模运算符 c 遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28093465/