简体   繁体   English

多个if else语句的更好方法?

[英]Better approach for multiple if else statements?

I have a program that takes in 3 numbers (feet, inches, sixteenths) then multiplies them by x . 我有一个程序,它接受3个数字(英尺,英寸,十六分之一),然后将它们乘以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. 我的问题是,既然总数的十六分之一可能超过4-5百,那么如果不这样做的if else ,那将是很多。 Is there a better way to do this? 有一个更好的方法吗?

Remive all the if/else statements and use integer arithmetic instead. 删除所有的if / else语句,并改用整数算术。

This is equivalent code for all your code: 这是所有代码的等效代码:

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

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

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