因此,我正在构建一个程序,在其中我使用不同的硬币并将其价值打印为美元和美分。由于我需要每个都是整数,因此我做了一些编码。我的问题是,在某些情况下,运行该程序时,我的美分价值出现了错误。一切都是正确的。我假设这与转换为整数有关,并且在给定某些用户输入时,它不会舍入。例如,当我输入10个季度,3个角钱,6个镍币和2个便士时,它的末尾为11美分。我无法在这里找出错误。
我的完整代码如下。谁能让我知道我做错了什么?
public static void main (String[]args){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of quarters: ");
double qs=sc.nextDouble();
System.out.print("Enter the number of dimes: ");
double ds=sc.nextDouble();
System.out.print("Enter the number of nickels: ");
double ns=sc.nextDouble();
System.out.print("Enter the number of pennies: ");
double ps=sc.nextDouble();
System.out.print("\n");
double qV=0.25;
double dV=0.10;
double nV=0.05;
double pV=0.01;
double tQ=qs*qV, tD=ds*dV, tN=ns*nV, tP=ps*pV;
double totalV=tQ+tD+tN+tP;
int dollars=(int)totalV;
double cent=(totalV-dollars)*100;
int cents=(int)cent;
int tqs=(int)qs;
int tds=(int)ds;
int tns=(int)ns;
int tps=(int)ps;
System.out.println("You entered "+tqs+" quarters.");
System.out.println("You entered "+tds+" dimes.");
System.out.println("You entered "+tns+" nickels.");
System.out.println("You entered "+tps+" pennies.");
System.out.print("\n");
System.out.println("Your total is "+dollars+" dollars and "+cents+" cents.");
}
美好的一天,
获得所需内容的正确方法是使用Math.round()方法,如下所示:
int cents= (int) Math.round(cent);
对于您的美元价值,我将采用相同的方法。您可能会阅读有关IEEE 754计算的更多信息,这是一个很好的解释,说明幕后的情况-Java浮点基元是否有IEEE 754标准实现?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句