简体   繁体   中英

Better approach for multiple if else statements?

I have a program that takes in 3 numbers (feet, inches, sixteenths) then multiplies them by x . Upon starting to write the output part, I ran into needing:

if (sixteenths4<16) {
    sixteenths5=sixteenths4;
    inches6=0;
}else if (16<=sixteenths4) {
    sixteenths5=sixteenths4-16;
    inches6=1;
}else if (32<=sixteenths4) {
    sixteenths5=sixteenths4-32;
    inches6=2;
}else if (48<=sixteenths4) {
    sixteenths5=sixteenths4-48;
    inches6=3;
} else {
    sixteenths5=sixteenths4-64;
    inches6=4;
    }

I realize the last else is redundant as it will never happen. My issue is that since the total sixteenths could exceed 4-5 hundred, that would be a lot of if else blocks. Is there a better way to do this?

Remive all the if/else statements and use integer arithmetic instead.

This is equivalent code for all your code:

sixteenths5 = sixteenths4 % 16;
inches6 = sixteenths4 / 16;

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