首页 > 解决方案 > 计算货币数量的代码认为它很古怪。(意外的小数不断出现)

问题描述

我刚开始通过 CodeAcademy 学习 C#。我应该编写一个程序来计算达到指定数量所需的不同价值的“硬币”的最少数量。按照说明一切都很好,但在练习结束时,我们鼓励您编写更多代码以使程序使用十进制输入(而不仅仅是整数)。

我基本上复制了用于完整金额的相同代码,稍作修改(将初始金额乘以 100),以便它仍然可以运行并给出所需的结果。但是,由于某种原因,最后一个值(青铜美分)一直给我带小数的数字。我考虑过使用 Math.Floor() 但经过几次试验后,我意识到它并不总是多余的。谁能提供一些帮助?我应该知道的 Math.Floor() 命令是否存在任何固有限制?我是不是做了个大傻事?

tl;博士:这里的新手编码器,想知道为什么代码不能做我想做的事

using System;

namespace MoneyMaker
 {
class MainClass
{
public static void Main(string[] args)
{
  // This code is meant to divide an (user given) amount of money into coins of different values.

  // First we ask for an input.
  Console.WriteLine("Welcome to Money Maker!.00");
  Console.WriteLine("Please enter the amount you want to divide in Coins:");
  string strAmount = Console.ReadLine();
  Console.WriteLine($"${strAmount} Canopy is equal to:");
  double wholeAmount = Convert.ToDouble(strAmount);

  // These are the values of each coin.
  // The cents are multiplied by 100 for the purposes of using then in the code.
  // The bronze coins are listed, but unused, since their value is essentially 1.
  double gold = 10;
  double silver = 5;
  //double bronze = 1;
  double smolGold = .1 * 100;
  double smolSilver = .05 * 100;
  //double smolBronze = .01 * 100;

  // These lines calculate the integral values (gold, silver and bronze coins).
  double douAmount = Math.Floor(wholeAmount);
  double goldCoins = Math.Floor(douAmount / gold);
  double silAmount = douAmount % gold;
  double silverCoins = Math.Floor(silAmount / silver);
  double bronzeCoins = silAmount % silver;

  // These lines calculate the decimal values (gold, silver and bronze cents).
  // They start by multiplying the cents by 100, rendering the rest of the lines the same as in the integral values.
  double smolAmount = 100 * (wholeAmount - douAmount);
  double goldCents = Math.Floor(smolAmount / smolGold);
  double littleSilver = smolAmount % smolGold;
  double silverCents = Math.Floor(littleSilver / smolSilver);
  //ERROR: There seems to be an issue with the bronze cents, returning a value with decimals.
  double bronzeCents = littleSilver % smolSilver;

  // Finally, the output string with the results:
  Console.WriteLine($"\n Gold Coins: {goldCoins} \n Silver Coins: {silverCoins} \n Bronze Coins: {bronzeCoins} \n Gold Cents: {goldCents} \n Silver Cents: {silverCents} \n Bronze Cents: {bronzeCents}");
}

} }

标签: c#

解决方案


永远不要使用双打货币。使用decimal.

double在表示物理量(如长度、质量、速度等)时使用,其中无关紧要的表示错误无关紧要。用来decimal代表金钱,每一分钱或一分钱都很重要。

区别在于:double将数字表示为分数,其中分母是 2 的幂,例如“5/32nds”。 decimal将数字表示为分数,其中分母是 10 的幂,例如“3/100ths”。前者往往会累积像“3/100ths”这样的分数的表示错误,但后者不会。

如果您的教程建议您使用double算术进行涉及金钱的计算,请获取更好的教程

综上所述,我怀疑%如果您在非整数数量上使用运算符,您可能会误解运算符的用途。它主要用于整数数量,所以如果你在小数或双精度数上使用它,可能会发生一些奇怪的事情。


推荐阅读