wahoozie
wahoozie

Reputation: 29

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?

Upvotes: 2

Views: 114

Answers (1)

Bohemian
Bohemian

Reputation: 424973

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;

Upvotes: 4

Related Questions