英文:
Why does it always display the wrong amount of nickels?
问题
我正在编写一个 Java 方法,它接收一个范围在1-99之间的整数。它可以正确显示25美分和10美分硬币的数量,但无法正确显示5美分的硬币。这个类名叫做 PS1。
static void problem10(int change)
{
if (change > 99)
{
return;
}
//声明变量
int numQuarters;
int numDimes;
int numNickels;
int numPennies;
//计算每个面额的硬币数量
numQuarters = change / 25;
if (numQuarters <= 0.1){
numQuarters = 0;
}
numDimes = (change - numQuarters*25) /10 ;
if (numDimes <= 0.1){
numDimes = 0;
}
numNickels = (change - numQuarters * 25) - (numDimes * 10) / 5; //修正5美分硬币部分
if (numNickels < 1){
numNickels = 0;
}
numPennies = (change - numQuarters * 25) - (numDimes * 10) - (numNickels * 5) / 1;
if (numPennies < 1){
numPennies = 0;
}
//打印每个面额的正确找零数量
System.out.println("您的找零为 " + numQuarters + " 个25美分硬币 " + numDimes + " 个10美分硬币 " + numNickels + " 个5美分硬币 " + numPennies + " 个1美分硬币 ");
}
对于PS1.problem10(35);,它的输出是:
您的找零为 1 个25美分硬币 1 个10美分硬币 8 个5美分硬币 0 个1美分硬币
英文:
I'm making a Java method that takes in an int from 1-99. It can correctly display quarters and dimes, but will not correctly display the nickels. The class is PS1
static void problem10(int change)
{
if (change > 99)
{
return;
}
//declaring variables
int numQuarters;
int numDimes;
int numNickels;
int numPennies;
//figuring out change for each denomination
numQuarters = change / 25;
if (numQuarters <= 0.1){
numQuarters = 0;
}
numDimes = (change - numQuarters*25) /10 ;
if (numDimes <= 0.1){
numDimes = 0;
}
numNickels = (change - numQuarters * 25) - (numDimes * 10) / 5; //fix nickels
if (numNickels < 1){
numNickels = 0;
}
numPennies = (change - numQuarters * 25) - (numDimes * 10) - (numNickels * 5) / 1;
if (numPennies < 1){
numPennies = 0;
}
//printing the correct change for each denomination
System.out.println("Your change is " + numQuarters + " quarters " + numDimes + " dimes " + numNickels + " nickels " + numPennies + " pennies ");
}
The output it gives for PS1.problem10(35); is:
Your change is 1 quarters 1 dimes 8 nickels 0 pennies
答案1
得分: 0
需要额外的括号,如下所示:
numNickels = ((change - numQuarters * 25) - (numDimes * 10)) / 5; # 修正 nickels
if (numNickels < 1):
numNickels = 0
numPennies = ((change - numQuarters * 25) - (numDimes * 10) - (numNickels * 5)) / 1
if (numPennies < 1):
numPennies = 0
英文:
need extra parentheses like;
numNickels = ((change - numQuarters * 25) - (numDimes * 10)) / 5; //fix nickels
if (numNickels < 1){
numNickels = 0;
}
numPennies = ((change - numQuarters * 25) - (numDimes * 10) - (numNickels * 5)) / 1;
if (numPennies < 1){
numPennies = 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论