c - C - Float Imprecision,如何锁定计算的小数位?
问题描述
我正在做一个小程序来测试C中的浮点数:程序本身很简单,我只想根据用户的输入,返回多少Dollar(s), Quarter(s)... etc
,他的号码有。
//------------------------------> First Part: All the necessary Variables <-----------------------------
int main (void)
{
//Getting the user Input
float number = get_float("Number: ");
//Checking if is a positive number
if (number < 0)
{
printf("A positive number, Please: ");
}
//Declaring my Constant/Temporary variables.
float coinValues[] = {1.00, 0.25, 0.10, 0.5, 0.01};
char *coinNames[] = {"Dollar(s): ", "Quarter(s): ", "Dime(s): ", "Nickel(s): ", "Penny(ies): "};
int i = 0;
int tmp = 0;
//-----------------------------------> Second Part: The code Itself <-----------------------------------
//Checking/Printing the necessary coins.
while (number > 0)
{
//Until the loop stops, check if the number can be divided by the CoinValue.
if (number >= coinValues[i])
{
//Print the current Coin Name from the divided value.
printf("%s", coinNames[i]);
//Check if the Current Number still contains Coin Values inside of it, if True counts one in your "Coin Score".
while (number >= coinValues[i])
{
number -= coinValues[i];
tmp++;
}
//Print the Current "Coin Score", then resets TMP.
printf("%i\n", tmp);
tmp = 0;
}
else
{
//Updating the Coin value
i++;
}
}
}
只要我使用Integers,我的程序运行得非常好,但是当我将此代码转换为Floats时,值开始在Int变量tmp(Dime(s), Nickel(s), and Penny(ies))
中返回非预期结果。
像2.6这样的数字的预期结果将是2 Dollars、2 Quarters和1 Dime,但有时,程序不使用Dime(s),而是跳过它们并使用Nickel(s)进行操作,困扰我的是程序总是返回AWL=+没有任何价值,然后程序永远冻结。
考虑到我唯一的想法是我“遭受”了Float Imprecision,而且我不知道如何解决它,所以有人可以帮助我吗?
附言。在传递之前,程序需要始终返回每个硬币的最大值。
解决方案
浮点运算旨在逼近实数运算。IEEE 754-2008 说“浮点算术是实数算术的系统近似……”所以没有办法在二进制浮点中“锁定”十进制数字。它旨在用于您需要近似值的地方,例如建模物理。这甚至包括一些金融应用,例如期权评估。尽管在某些情况下可以使用浮点运算进行精确计算,但这些需要特别小心,并且通常只在特殊情况下进行。
因此,关于如何锁定小数位的问题的答案是没有好的方法可以用二进制浮点来做到这一点。尝试这样做通常只会产生与整数算术相同的效果,但效率较低且代码更难。因此,请使用整数算术并根据所需的最小货币单位(例如一美分)调整金额。
推荐阅读
- vb.net - 通过路径而不是字节内容访问资源 - VB.NET
- angular - Angular 6 - 通用输入(更改)方法,如何判断修改了哪个模型值?
- javascript - 获取脚本中字符串的第一个数字
- mfc - 将 CComboBox 与 CTaskDialog 上的 CRadioButton 选项相关联
- python - 回文类 -- NameError: name 'is_palindrome' is not defined
- python-3.x - 如何使用变量“保存”字符串值作为列表名称?
- node.js - 如何使用 node.js 从 Azure 聊天机器人对话窗口收集反馈
- plupload - 如何在 PL UPLOAD API 文件上传中添加或使用自定义过滤器?
- content-management-system - 成功安装后未打开magento仪表板登录面板
- java - 石英如何确保只有一个节点运行作业