【发布时间】:2020-12-28 02:16:22
【问题描述】:
因此,基本上,现金是一个问题,您需要编写一个程序来计算固定金额中有多少硬币。
例如:对于 0.41 美元,您可以欠的最低硬币为 4(1 夸特,1 角钱,1 镍,1 便士)。
该练习将要求您编写一些可以回答的问题:4 表示条目“0.41”
我对程序进行了一些更改,因此它的答案是 4.2$,例如: "16 个季度 2 毛钱 0 镍 0 penny(ies)" 并且想知道是否有办法优化代码并使其变得更好? 这是代码:
#include <cs50.h>
#include <math.h>
int main(void)
{
//Prompt user for an amount of change
float n;
do
{
n = get_float("How much change is owed for : (in $)\n");
//Verify if the float is positive
}
while (n < 0);
//Multiply 'n' by 100 to avoid float imprecisions
int cent = round(n * 100);
// Initialize the number of quarters (zero initially)
int quarters = 0;
while (cent >= 25)
{
quarters++;
cent = cent - 25;
}
// Initialize and calculate the number of dimes (zero initially)
int dimes = 0;
while (cent >= 10)
{
dimes++;
cent = cent - 10;
}
// Initialize and calculate the number of nickels (zero initially)
int nickels = 0;
while (cent >= 5)
{
nickels++;
cent = cent - 5;
}
// Initialize and calculate the number of pennies (zero initially)
int pennies = 0;
while (cent >= 1)
{
pennies++;
cent = cent - 1;
}
//Print the results
printf("%i quarter(s)\n", quarters);
printf("%i dime(s)\n", dimes);
printf("%i nickel(s)\n", nickels);
printf("%i penny(ies)\n", pennies);
}
【问题讨论】:
-
您可以使用除法来获取每个硬币的数量,而不是一个接一个地循环计数。
-
这听起来像是属于code review
-
@MikeCAT 因为我是编程的初学者,我希望你能输入一些伪代码来帮助我弄清楚你说的是什么。在此先感谢:D
-
@Kevin 嗨,这是我的第一篇文章,如果它不属于这里,我真的很抱歉,仍在弄清楚 stackoverflow 是如何工作的
-
@wildplasser 问题的目的是使用 get_float 和
int cent = round(n * 100);来避免不精确