根据两个输入计算纸币和硬币的变化

标签 c math precision integer-arithmetic

我有一项学校作业,需要在提供两个输入(即元素成本和投标金额)后计算纸币和硬币的变化。在说明中,提到了一个测试用例,上面写着

Please include as a test a case in which the number of dollars, if multiplied by 100.0 and cast to int without the tiny amount added in, would be just short of the correct integer number of pennies.

当它说缺少正确的便士整数时,我不确定它到底需要什么。 如果有人可以解释,那将会非常有帮助。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
  double dcost, dtendered;
  int    icost, itendered;
  int    itwenties, itens, ifives, iones, iquarters, idimes, inickels, ipennies;
  /* add any additional variables between here -> */
  int itotal;
  /* <- and here*/

  scanf("%lf", &dcost);
  scanf("%lf", &dtendered);

  icost     = (int)((dcost * 100.0) + 0.000001);
  itendered = (int)((dtendered * 100.0) + 0.000001);

  /* add code to calculate itwenties, itens, etc., between here -> */
  itotal    = itendered - icost;
  itwenties = itotal / 2000;
  itotal    = itotal % 2000;
  itens     = itotal / 1000;
  itotal    = itotal % 1000;
  ifives    = itotal / 500;
  itotal    = itotal % 500;
  iones     = itotal / 100;
  itotal    = itotal % 100;
  iquarters = itotal / 25;
  itotal    = itotal % 25;
  idimes    = itotal / 10;
  itotal    = itotal % 10;
  inickels  = itotal / 5;
  itotal    = itotal % 5;
  ipennies  = itotal;

  /* <- and here */

  printf("%2d twenties\n", itwenties);
  printf("%2d tens\n", itens);
  printf("%2d fives\n", ifives);
  printf("%2d ones\n", iones);
  printf("%2d quarters\n", iquarters);
  printf("%2d dimes\n", idimes);
  printf("%2d nickels\n", inickels);
  printf("%2d pennies\n", ipennies);

  while (1)
    getchar();
  return 0;
}      

在第 23、24 行中,我添加了少量内容

编辑:我在此链接上附上此作业的说明表 请看一次。 https://docs.google.com/document/d/1RolSvpg5Purn4_IrhG1cbrrcSwHjYvnDcIZQ3uoQM8U/edit?usp=sharing

最佳答案

提示要求您计算整美元的金额,在不使用 + 0.000001 的情况下进行转换时,结果是减去 1 美元加上 99 美分。
IE。您可能应该意识到计算机上 float 学的不精确问题。

您不需要在程序中执行此操作,相反,您应该正确转换。

但是,您应该有一个测试用例,可以检测代码是否无法使用少量进行正确转换。

这意味着,如果你提交了基本正确的程序,它将用这样的数量进行测试。如果该测试(否则可能被视为边缘情况)失败,那么您不仅犯了一个小错误,而且还没有按照明确规定的要求进行工作。
我想这对你的成绩意味着更大的惩罚......

关于根据两个输入计算纸币和硬币的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038204/

相关文章:

c# - 以微秒为单位的日期时间

math - 如何将彩色点从 2D 图像移动到 3D 球体

c - 手动 Math.pow() 使用 float 失去精度

c++ - 用于检查 C/C++ 代码约定的自动工具

c - 如何正确使用 sscanf?

algorithm - 常见的会面点,包括人流

python - 为什么 pow(num, power, mod) 比 (num ** power) % mod 快得多?

PostgreSQL:float(1) 和 float(24) 有什么区别?

iphone - AudioQueue 吃掉了我的缓冲区(前 15 毫秒)

c - 如何处理具有多个退出点的函数的函数退出?