是否可以改变这种“开关”?首先我虽然可以使用'for'代替,但我认为不再需要了。目标是使此代码更有效。有谁知道如何进行这项改进,以提高代码效率?我还在学习编程,我不是那么有经验。我已经做了一些事情,但我不知道它是否缺少我把新代码置于旧代码之下的东西。我认为可能有必要使用if而不是for I created或其他函数,因为我无法更改'PageNumber'的值我只需要使用它。也许我不需要使用“案例”内部的任何内容。有人可以澄清一下吗?
switch (PageNumber) {
case 0x01:
m = 0;
for (n = 0; n < 8; n++) {
if (n < NumberOfSensor) {
if (n < 4) {
Write_string("L ", n, 0);
Write_int((n + 1), n, 1);
write_CustonCharacter(4, n, 3); //Write the indicator "->"
Write_int(Sensor_Count[n], n, 5);
} else if (n > 3) {
Write_string("L ", (n - 4), 10);
Write_int((n + 1), (n - 4), 11);
write_CustonCharacter(4, (n - 4), 13); //Write the indicator "->"
Write_int(Sensor_Count[n], (n - 4), 15);
}
}
}
break;
/*
* PAGE 2
*/
case 0x02:
m = 0;
for (n = 8; n < 16; n++) {
if (n < NumberOfSensor) {
if (n < 12) {
Write_string("L ", (n - 8), 0);
Write_int((n + 1), (n - 8), 1);
write_CustonCharacter(4, (n - 8), 3); //Write the indicator "->"
Write_int(Sensor_Count[n], (n - 8), 5);
} else if (n > 11) {
Write_string("L ", (n - 12), 10);
Write_int((n + 1), (n - 12), 11);
write_CustonCharacter(4, (n - 12), 13); //Write the indicator "->"
Write_int(Sensor_Count[n], (n - 12), 15);
}
}
}
break;
//...(This part is just repetition)
/*
* PAGE 8
*/
case 0x08:
m = 0;
for (n = 56; n < 65; n++) {
if (n < NumberOfSensor) {
if (n < 60) {
Write_string("L ", (n - 56), 0);
Write_int((n + 1), (n - 56), 1);
write_CustonCharacter(4, (n - 56), 3); //Write the indicator "->"
Write_int(Sensor_Count[n], (n - 56), 5);
} else if (n > 59) {
Write_string("L ", (n - 60), 10);
Write_int((n + 1), (n - 60), 11);
write_CustonCharacter(4, (n - 60), 13); //Write the indicator "->"
Write_int(Sensor_Count[n], (n - 60), 15);
}
}
}
break;
default:
break;
}
//==========================================================================
for (PageNumber = 1; PageNumber < 9; PageNumber++) { //actually I think this for is not necessary because it receives PageNumber and then it does what it needs to do.
m = 0; //but does it need something else?
for (n = (PageNumber * 8 - 8); n < (PageNumber * 8); n++) {
if (n < NumberOfSensor) {
if (n < (PageNumber * 8 - 4)) {
Write_string("L ", n - (PageNumber * 8 - 8), 0);
Write_int((n + 1), n - (PageNumber * 8 - 8), 1);
write_CustonCharacter(4, n - (PageNumber * 8 - 8), 3); //Write the indicator "->"
Write_int(Sensor_Count[n], n - (PageNumber * 8 - 8), 5);
} else if (n > (PageNumber * 8 - 5)) {
Write_string("L ", n - (PageNumber * 8 - 4), 10);
Write_int((n + 1), n - (PageNumber * 8 - 4), 11);
write_CustonCharacter(4, n - (PageNumber * 8 - 4), 13); //Write the indicator "->"
Write_int(Sensor_Count[n], n - (PageNumber * 8 - 4), 15);
}
}
}
}
首先,我会说这段代码效率不高主要是因为它重复自身,而不是因为内存使用。
如何在这方面改进它 - 你只能有一个for-loop而没有switch-case。
怎么样?尝试在每种情况下表示for循环作为case的值的函数,然后根据其他for循环体来概括它。例如:
请注意,对于每种情况:
(PageNumber-1)*8
n < PageNumber*8
if-then
条款中的第一行始终是Write_string("L ", (n-((PageNumber-1)*8), 0));
等等。继续推广作为PageNumber
函数更改的每个数字,然后你最终只有一个for循环而没有switch-case。