有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何修复税率操作?

目标是提供总销售额,但是,税率计算不正确,因为它一直输出0.0

import java.util.Scanner; //Required for axquiring user's input

public class salesTax {

    public static void main(String[] args) {
        int retailPrice; //Holds the retail price
        int taxRate; //Holds sales tax rate
        double salesTax; //Holds sales tax
        double totalSale; //Holds total sale
        
        //Scanner object to acquire user's input
        Scanner input = new Scanner(System.in);
        
        //Acquire user's retail price
        System.out.println("What is the retail price of the item being purchased? ");
        retailPrice = input.nextInt();
        
        //Acquire user's sales tax rate
        System.out.println("What is the sales tax rate? ");
        taxRate = input.nextInt() / 100;
        
        //Display the sales tax for the purchase
        salesTax = retailPrice * taxRate; //Calculates the sales tax
        System.out.println("The sales tax for the purchase is: " + salesTax);
        
        //Display the total of the sale
        totalSale = retailPrice + salesTax; //Calculate the total sale
        System.out.println("The total of the sale is: " + totalSale);
    }
}

如果税率是由用户输入的,是否有办法确定税率以产生准确的计算结果


共 (3) 个答案

  1. # 1 楼答案

    您的税率必须是double,因为您要将其除以100,然后将其赋值taxRate。由于税率是一个int,它将截断该值,只留下整数值

    如果taxRate = 7然后除以100,得到0.07。由于taxRate是一个整数值,当Java看到所说的0.07时,它将去掉小数,只留下整数。因此,假设taxRate = 3.9999,由于taxRate是一个int,它将截断离开3的值。要解决此问题,请将taxRate更改为double

    此外,还需要将taxRate读取为双精度值。要使用Scanner读取双精度值,它将是taxRate = input.nextDouble() / 100;

  2. # 2 楼答案

    taxRate = input.nextInt() / 100;
    

    这将给您0,因为您正在被整数除。您可以将数字作为浮点数输入,然后除以100

    float taxRate;
    taxRate = input.nextFloat() / 100;
    
  3. # 3 楼答案

    要计算税率,您需要从System输入中读取一个整数,然后将其除以100得到一个整数结果,我认为您输入的值小于100。您需要从scanner读取值作为float

    请尝试以下方法:

    float taxRate;
    taxRate = input.nextFloat() / 100;
    

    编辑:

    如注释中所述,taxRate值介于01之间,因此您应该将taxRate声明为floatdouble