c - 最少的硬币数量
问题描述
请找到问题上下文如下:
编写一个程序,接受一个表示金额的浮点值,例如 2.8 表示 2 美元和 80 美分。然后程序应显示偿还硬币金额所需的最小硬币数量。假设用户输入的值大于 0 小于 10。
#include <stdio.h>
int main(void) {
double amt;
printf("Enter amount:");
scanf("%lf", &amt);
int amt_cents;
amt_cents = amt * 100;
int dollar_1;
dollar_1 = amt_cents / 100;
amt_cents = amt_cents - (dollar_1 * 100);
int cents_50;
cents_50 = amt_cents / 50;
amt_cents = amt_cents - (cents_50 * 50);
int cents_20;
cents_20 = amt_cents / 20;
amt_cents = amt_cents - (cents_20 * 20);
int cents_10;
cents_10 = amt_cents / 10;
amt_cents = amt_cents - (cents_10 * 10);
int cents_05;
cents_05 = amt_cents / 5;
amt_cents = amt_cents - (cents_05 * 5);
int cents_01;
cents_01 = amt_cents / 1;
amt_cents = amt_cents - (cents_01 * 1);
if (dollar_1 != 0) {
printf("Number of 1$: %d\n", dollar_1);
}
if (cents_50 != 0) {
printf("Number of 50c: %d\n", cents_50);
}
if (cents_20 != 0) {
printf("Number of 20c: %d\n", cents_20);
}
if (cents_10 != 0) {
printf("Number of 10c: %d\n", cents_10);
}
if (cents_05 != 0) {
printf("Number of 5c: %d\n", cents_05);
}
if (cents_01 != 0) {
printf("Number of 1c: %d\n", cents_01);
}
}
输出:
输入金额:1.1 1$ 的数量:1 10c 的数量:1
输入金额:2.1 1$ 的数量:2 10c 的数量:1
输入金额:3.1 1$ 的数量:3 10c 的数量:1
输入金额:4.1 1$ 的数量:4 5c 的数量:1 1c 的数量:4
输入金额:5.1 1$ 的数量:5 5c 的数量:1 1c 的数量:4
输入金额:6.1 1$ 的数量:6 10c 的数量:1
问题: 为什么 4.1 和 5.1 的值与 0 - 10 范围内的所有其他值的工作方式不同?通过手动计算代码,似乎 4.1 和 5.1 应该与所有其他情况一致,仅为 10c 生成值 1,但在执行程序时情况并非如此。
解决方案
为什么 4.1 和 5.1 的值与 0 - 10 范围内的所有其他值的工作方式不同?
因为浮点数并不总是准确地表示值。看看这段代码:
double amt;
printf("Enter amount:");
scanf("%lf", &amt);
int amt_cents;
amt_cents = amt * 100;
如果您在最后一行之后设置断点并检查您的值,amt_cents
您可能会发现它409
不是410
您所期望的,因为amt
类似于4.09999999...
.
您需要将数字四舍五入到最接近的整数,而不是只取整数部分,一种简单的方法是在值上加上 0.5,然后截断:
amt_cents = amt * 100.0 + 0.5;
推荐阅读
- ethereum - 向 Ropsten RPC 错误添加流动性:执行恢复:TransferHelper:TRANSFER_FROM_FAILED
- delphi - 为什么 Delphi 在添加新语言时会为项目的每个配置创建一个单独的 .rc 文件?
- java - 如何使用 Firebase ML Kit 文本识别检测图像中的小数
- python - TensorFlow 动态填充
- firebase - 文本小部件将实时 Fireabase 值检测为空
- python - Tkinter Button 通过单击鼠标具有打开和关闭功能
- python - kivy冻结屏幕
- twitter-oauth - Twitter oauth_signature 需要 urlencode(百分比十六进制编码)在签名库中的回调 url 上运行两次
- javascript - 脚本中未处理的 Promise Rejection
- java - 将 SQL 查询转换为 HQL、Java Hibernate 时出错