条件语句if else java中的逻辑错误

k3fezbri  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(304)

我有一个给定的问题,那就是:电脑租赁有一个固定的收费每小时的头三个小时或更少。超过三小时的费用将按每小时正常费用的10%收取。我的源代码是:

System.out.print("ENTER REGULAR CHARGE: ");
    int charge = scan.nextInt();

    System.out.print("ENTER REGULAR HOURS: ");
    int hours = scan.nextInt();

    scan.close();

    if (hours <= 3)
    {
        int bill= charge * hours;
        System.out.print("RENTAL BILL IS: " +bill);
    }
    else
    {
        double bill = (double) (charge * hours)-0.10;
        System.out.print("RENTAL BILL IS: " +bill);
    }

预期产量应为:

ENTER REGULAR CHARGE: 4
ENTER REGULAR HOURS: 10
RENTAL BILL IS: 39

但我的结论是:

ENTER REGULAR CHARGE: 4
ENTER REGULAR HOURS: 10
RENTAL BILL IS: 39.9

我不知道我的公式或者我使用的变量有没有问题。如果有人指出我源代码中的错误,那将非常有帮助。

57hvy0tb

57hvy0tb1#

您需要计算3小时的价格,并从第二种情况下的总小时数中扣除。同时对原始价格进行折扣,将其乘以剩余工时,再将这些工时价格加上3小时价格。
代码如下

import java.util.Formatter;
import java.util.Scanner;
public class string{
public static void main(String[] args){

    double bill= 0;
    Scanner scan = new Scanner(System.in);

    System.out.print("ENTER REGULAR CHARGE: ");
    double charge = scan.nextInt();

    System.out.print("ENTER REGULAR HOURS: ");
    int hours = scan.nextInt();

    scan.close();

    if (hours <= 3){
        // calculation for 3 hours or less
        bill= charge * hours;
        System.out.print("RENTAL BILL IS: " +bill);
    }
    else {
        // subtracting 3 hours from total hours if hours are more                              
        int remainingHrs = hours - 3; 

        // calculating price for 3 hours to add to remaining hours price                                         
        double priceforthreeHours = charge * 3;

        // calculating discountedprice (10% discount)
        double discprice = charge - (charge * 0.10);

        // adding it all together 3hrs + discounted price                                                        
        bill = priceforthreeHours +(remainingHrs * discprice);

        System.out.print("RENTAL BILL IS: ");

        // formatting price using java.util.Formater
        System.out.printf(" %.2f, %n",bill); 

    }
}

}

相关问题