简体   繁体   English

您能帮我改善一下吗?

[英]Can you help me to improve this?

I want to improve this part of a code, I was thinking about using for: 我想改进代码的这一部分,我当时正在考虑将其用于:

        if((0 < NumberOfSensor) && (NumberOfSensor< 9))MaxPageNumber = 1;
        if((8 < NumberOfSensor) && (NumberOfSensor< 17))MaxPageNumber = 2;
        if((16 < NumberOfSensor) && (NumberOfSensor< 25))MaxPageNumber = 3;
        if((24 < NumberOfSensor) && (NumberOfSensor< 33))MaxPageNumber = 4;
        if((32 < NumberOfSensor) && (NumberOfSensor< 41))MaxPageNumber = 5;
        if((40 < NumberOfSensor) && (NumberOfSensor< 49))MaxPageNumber = 6;
        if((48 < NumberOfSensor) && (NumberOfSensor< 57))MaxPageNumber = 7;
        if((56 < NumberOfSensor) && (NumberOfSensor< 65))MaxPageNumber = 8;

You didn't indicate the data types of your variables, but based upon the context, I'll assume they are of an integer type. 您没有指示变量的数据类型,但是根据上下文,我将假定它们是整数类型。 Since all of your integer interval checks are the same "width" you can replace the multiple range checks with a calculation and one conditional: 由于所有整数间隔检查都具有相同的“宽度”,因此您可以用一种计算和一种条件替换多个范围检查:

if (NumberOfSensor > 0 && NumberOfSensor < 65)
    MaxPageNumber = (NumberOfSensor + 7) / 8;

Again, this assumes the variables are of integer type. 同样,这假设变量是整数类型。 In C, when dealing strictly with integer arithmetic and assignment, integer division takes the floor of the result, so for example, 9/8 results in 1. 在C语言中,当严格处理整数算术和赋值时,整数除法将结果作为下限 ,例如9/8等于1。

Your code doesn't change MaxPageNumber if NumberOfSensor is <= 0, or > 64. Thus, the if conditional is still needed if you want the code to behave exactly the same way as the original. 您的代码不会改变MaxPageNumber如果NumberOfSensor <= 0或> 64。因此, if有条件的,如果你想要的代码的行为完全相同的方式与原来相同,仍然需要。

Note that the above calculation has the same result as the calculation posted in the other answer. 请注意,上述计算结果与其他答案中发布的计算结果相同。 Either one will do. 任一个都会做。

我假设NumberOfSensor是1到64之间的整数。如果是这种情况,则可以简单地使用:

MaxPageNumber = ((NumberOfSensor-1) / 8) + 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM