繁体   English   中英

在尝试计算总价时,如何将我的双精度错误代码修复为 integer 错误代码? [复制]

[英]How do I fix my double to integer error code when trying to figure out total price? [duplicate]

到目前为止,我是一个初学者,在上完 5 节课后有点不知所措。 我收到以下行的“无法从双精度转换为整数”错误消息:“priceDozen = totalDozen * PRICEPERDOZEN;” & "priceLoose = totalLoose * PRICEPERLOOSE;" 我不知道我需要做什么来解决这个问题。 我是否以某种方式转换? 感谢您的任何建议!

package edu.mtc.egr281.chapter02;

导入 javax.swing.JOptionPane;

公共 class Project03 {

// Constants
public static final int DOZEN = 12;
public static final double PRICEPERDOZEN = 4.05;
public static final double PRICEPERLOOSE = 0.35;

public static void main(String[] args) {
    
    // PREPARE - Store Data
    int amount, priceDozen, priceLoose, totalDozen, totalLoose, totalPrice, totalEggs;
    
    // INPUT Data
    // Enter amount of eggs to purchase
    String amountString = JOptionPane.showInputDialog(
                            "Welcome to Meadowdale Dairy Farm!" +
                            " How many eggs would you like to purchase?");
    
    // Convert from String data type to the int data type
    amount = Integer.parseInt(amountString);
    
    // PROCESS Data
    // Determine the number of dozens, loose, dozen price, and loose price
    // Store off the original starting amount
    totalEggs = amount;
    
    // Determine the total number of dozen
    totalDozen = amount / DOZEN;
    // Calculate the amount remaining after the dozen
    amount = amount % totalDozen;
    
    // Determine the total number of loose
    totalLoose = amount;
            
    // Determine the total Dozen price
    priceDozen = totalDozen * PRICEPERDOZEN;
    
    // Determine the total Loose price
    priceLoose = totalLoose * PRICEPERLOOSE;
    
    // Determine the total price
    totalPrice = priceDozen + priceLoose;
    
    // OUTPUT Data
    // Output the number of dozen and loose eggs
    JOptionPane.showMessageDialog(null,
                        "You ordered " + totalEggs + " eggs." +
                        "That's " + totalDozen + " dozen eggs at $4.05 per dozen and " +
                        totalLoose + " loose eggs at $0.35 each for a total of " + totalPrice);
    
    // Exit GUI program
    System.exit(0);

}// Ending bracket of method main

}// class Project03Eggs的结束支架

解决方案1:

您可以简单地将变量priceDozen声明为double而不是int

double priceDozen;

您将获得小数的精确结果

解决方案2:(转换为int)

如果priceDozen不需要小数,您可以将计算转换为 int:

priceDozen = (int) (totalDozen * PRICEPERDOZEN);

您将得到一个不带小数的数字



(其他两个变量priceLoosetotalPrice

暂无
暂无

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

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