简体   繁体   中英

Alternate to If…else-if

What is best way to reduce the line of code for many if...else-if statements. Apart from the switch case

if(a>0 && a<=5){
a=5;
}
else if(a>5 && a<=10){
a=10;
}
else if(a>10 && a<=15){
a=15;
}
else if(a>15 && a<=20){
a=20;
}
.
.
.
.
.
else if(a>95 && a<=100)
a=100;
}

I have gone through many posts but could not find the feasable solution.

a = Math.ceil(a / 5.0) * 5;

This should solve the problem in your case. Use the ceiling function of whatever language you are programming in. Here is documentation for it in java: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#ceil-double-

for your problem it could be like this :

a = Math.ceil(a / 5.0)*5;

for more information look at floor and ceil

these are in java , i don't know what language you are using , but there might floor and ceil function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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