2017-04-25 52 views
-3

我有一个数据文件格式为< 0:00> - < 19321>, < 1:00> - < 19324>,最大为< 24:00> - < 19648>,因此,目前为止每小时都有使用的总功率(总数递增),我应该计算使用的功率,找到平均值和最高功率使用情况及其指标(时间)(我不需要帮助找到其时间指标使用的最大功率)。我把问题追溯到第31行,但我不明白我为什么做错了。有人可以向我解释为什么第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 
+1

欢迎来到Stack Overflow!这听起来像你可能需要学习如何使用[调试器](https://en.wikipedia.org/wiki/Debugger)来遍历你的代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

+1

“为什么第31行代码没有保存用于阵列的功率值”。你如何得出这个结论?我们不能帮助完成这些不完整的信息和代码。请提供[mcve],包括确切的输入,预期的输出和实际的输出。 – kaylum

+0

感谢大家的帮助,我明白了。在摆脱了我不需要的额外变量之后,我发现我错误地放置了一个计数器,即第31行的u ++,并将它移到了use数组之外,这样我就先将值设置到数组中,然后更新计数器。这解决了我的许多问题。 –

回答

1

为了理解,你是怎么知道第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]); 

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

相关问题