import java.util.Scanner;
public class AddCoins {
/**
* Nick Jones
* 2/5/2015
* Ad Coins
*/
public static String getDollarAmount(double pen, double nic, double dim, double qua) {
double total;
String amount;
pen = pen%1;
nic = nic%5;
dim = dim%10;
qua = qua%25;
total = pen + nic + dim + qua;
amount = ("$" + total);
return amount;
}
public static void main(String[] args) {
double pen;
double nic;
double dim;
double qua;
String amount;
Scanner input = new Scanner (System.in);
System.out.println ("enter amount of pennies: ");
pen = input.nextInt();
System.out.println ("enter amount of nickles: ");
nic = input.nextInt();
System.out.println ("enter amount of dimes: ");
dim = input.nextInt();
System.out.println ("enter amount of quarters: ");
qua = input.nextInt();
amount = getDollarAmount(pen, nic, dim, qua);
System.out.println(amount);
}
}
该程序假设在主要参数中记录所有输入的变化量,然后将其转移到getDollerAmount();所以然后所有的变化都转换为它们的值,然后总计并设置为字符串数量,这样我就可以将金额返回主程序并输出它。但数学不对,不会给我输出。
例如
输入便士数量:
1
输入镍的数量:
1
输入硬币数量:
1
输入季度数量:
1
$ 3.0分
这应该是0.41美元但不是
答案 0 :(得分:0)
因此,在getDollarAmount
方法中,您有以下几行:
pen = pen%1;
nic = nic%5;
dim = dim%10;
qua = qua%25;
%
符号名为Modulus
,实际上不是您要查找的内容。它实际上是在将每个变量的剩余部分除以1,5,10,25之后。
因此,当您为每个硬币金额输入1时,它正在执行:
1%1=0 // because 1 divided by 1 has no remainder
1%5=1
1%10=1
1%25=1
total = 0+1+1+1 =3
你想要的是真正为每枚硬币获得适当的价值。这是通过将硬币数量乘以其值totalCoinValue = coinAmount * coinValue
这个方法应该是这样的:
public static String getDollarAmount(double pen, double nic, double dim, double qua) {
double total;
String amount;
pen = pen * 0.01;
nic = nic * 0.05;
dim = dim * 0.10;
qua = qua * 0.25;
total = pen + nic + dim + qua;
amount = ("$" + total);
return amount;
}