如何在没有if语句的情况下做出决定 [英] How to make a decision without an if statement

查看:227
本文介绍了如何在没有if语句的情况下做出决定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java课程,但我们还没有正式学习语句。我正在研究并看到这个问题:

I'm taking a course in Java and we haven't officially learned if statements yet. I was studying and saw this question:


编写一个名为pay的方法,接受两个参数:TA工资的实数,以及本周TA工作的小时数的整数。该方法应该返回支付TA的金额。例如,看涨期权(5.50,6)应返回33.0。对于8岁以上的任何小时,TA应该获得1.5倍正常工资的加班工资。例如,通话费(4.00,11)应该返回(4.00 * 8)+(6.00 * 3)或50.0。

Write a method called pay that accepts two parameters: a real number for a TA's salary, and an integer for the number hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive "overtime" pay of 1.5 times the normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0.

如何在不使用if语句的情况下解决这个问题?到目前为止,我已经得到了这个,但我坚持定期支付:

How do you solve this without using if statements? So far I've got this but I'm stuck on regular pay:

public static double pay (double salary, int hours) {

     double pay = 0;

     for (int i = hours; i > 8; i --) {
         pay += (salary * 1.5);
     }
}


推荐答案

到避免直接使用流控制语句,如 if ,而则可以使用 Math.min Math.max 。对于这个特殊的问题,使用循环也不会有效。

To avoid direct use of flow control statements like if or while you can use Math.min and Math.max. For this particular problem using a loop would not be efficient either.

它们在技术上可能使用if语句或等效语句,但是很多其他标准库调用也是如此你已经做了:

They may technically use an if statements or the equivalent, but so do a lot of your other standard library calls you already make:

public static double pay (double salary, int hours) {
     int hoursWorkedRegularTime = Math.min(8, hours);
     int hoursWorkedOverTime = Math.max(0, hours - 8);
     return (hoursWorkedRegularTime * salary) +
            (hoursWorkedOverTime  * (salary * 1.5));
}

这篇关于如何在没有if语句的情况下做出决定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆