计算货币金额的代码认为这很奇怪.(意外小数不断出现)

  • 本文关键字:小数 意外 金额 货币 代码 计算 c#
  • 更新时间 :
  • 英文 :


我刚开始通过CodeAcademy学习C#。我应该写一个程序来计算达到指定数量所需的不同价值的"硬币"的最小数量。在遵循说明的过程中,一切都很顺利,但在练习结束时,我们鼓励您再写一些代码,使程序能够使用十进制输入(而不仅仅是整数(。

我基本上复制了用于完整金额的相同代码,只做了一些修改(将初始金额乘以100(,这样它仍然可以运行并给出所需的结果但是,由于某种原因,最后一个值(青铜美分(一直给我带小数的数字。我曾想过使用Math.Flor((,但经过几次尝试后,我意识到它并不总是多余的。有人能提供一些帮助吗?Math.Flor((命令有没有我应该知道的固有限制?我刚才是不是做了个大傻事?

tl;dr:nob编码器在这里,想知道为什么代码不做我想让它做的事情

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}");
}

}}

永远不要使用双精度货币。使用decimal

当表示物理量时,如长度、质量、速度等,使用double,其中无关紧要的表示误差无关紧要。使用decimal表示货币,其中每一分钱或一分钱的一小部分都很重要。

不同之处在于:double将数字表示为一个分数,其中分母是二的幂,如"5/32nds"。decimal将数字表示为一个分数,其中分母是十的幂,如"3/100"。前者倾向于积累像"3/100ths"这样的分数的表示误差,但后者不会。

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

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

最新更新