我有一个格式为-,-的数据文件,直到-,所以每小时都有所使用的总电量到目前为止(总数已增加),我应该计算使用的功率,找到功率的平均值和最高使用率及其指数(时间),(我不需要在查找其最大使用功率时需要帮助时间索引)。我将问题追溯到第31行,但是我不明白为什么我做错了。有人可以向我解释为什么第31行中的代码没有将使用的功率值节省下来吗?以及我该如何解决?提前致谢!

 float compute_usage(int num, int vals[], int use[], int *hi_idx)
 15 {
 16         int i;// i is a general counter for all for loops
 17         int r1, r2, u, v, pow_dif, temp;//for loop 1
 18         int tot;//for loop 2
 19         int max_use, init, fina, diff;//for loop 3 //don't have to worry about this for loop, I am good here
 20         float avg;//average power used
 21
 22         for(r1=r2=i=u=v=0;i<num;i++)//for loop 1
 23         {
 24                 r1= vals[v++];//I set values of every hour as reading 1 & 2(later)
 25 #ifdef DEBUG
 26                 printf("pre-debug: use is %d\n", use[u]);
 27 #endif
 28                 if(r1!=0 && r2!=0)
 29                 {
 30                         pow_dif = (r1 - r2);//I take the to readings, and calculate the difference, that difference is the power used in the interval between a time period
 31                         use[u++] = pow_dif; //I'm suppose to save the power used in the interval in an array here
 32                 }
 33                 r2=r1;//the first reading becomes the second after the if statement, this way I always have 2 readings to calculate the power used int the interval
 34 #ifdef DEBUG
 35                 printf("for1-debug3: pow_dif is %d\n", pow_dif);
 36                 printf("for1-debug4: (%d,%d) \n", u, use[u]);
 37 #endif
 38
 39         }
 40         for(tot=i=u=0;i<num;i++)//for loop 2
 41         {tot = tot + use[u++];}
 42
 43         avg = tot/(num-1);
 44 #ifdef DEBUG
 45         printf("for2-debug1: the tot is %d\n", tot);
 46         printf("for2-debug2: avg power usage is %f\n", avg);
 47 #endif

最佳答案

只是为了了解,您如何得知第31行中的代码有问题?是第36行中的printf语句吗?

执行此操作时:

use[u++] = pow_dif; //I'm suppose to save the power used in the interval in an array here
printf("for1-debug4: (%d,%d) \n", u, use[u]);


在上一个操作(u ++)中,printf语句中的“ u”变量增加了,因此您正在浏览更改的元素。

use[u++] = pow_dif; //I.e. u=0 here, but u=1 after this is executed.
printf("...\n", u=1, use[1]);


在此循环中,“ i”是什么?为什么不在for语句中尝试使用“ u ++”而不是“ i ++”,并在使用赋值表达式中删除“ u ++”?

09-06 12:39