我想知道是否有办法使用Math.Round函数将值转换为0.05美分到5美分?我知道我可以通过将值乘以100来实现这一点,但我不想这样做,因为值存储在数组中并且在执行其他函数时会破坏其他计算。
例如,如果该值小于1美元,我希望打印出分值而不是小数,请参考下面的代码:
double[] coins = {0.05,0.10,0.20,0.50,1.00,2.00};
Console.WriteLine("Change is as follows:");
for (int j = 0; j < change_given.Length; j++)
{
if (change_given[j] == 0)
{
continue;
}
if (coins[j] < 1)
{
Console.WriteLine("{0} x {1}c", change_given[j], coins[j]);
}
else
{
Console.WriteLine("{0} x ${1}", change_given[j], coins[j]);
}
}
答案 0 :(得分:3)
看起来这只是出于显示目的。如果你乘以coins[j]*100
,你不会更新硬币[j]:
for (int j = 0; j < change_given.Length; j++)
{
if (change_given[j] == 0)
continue;
if (coins[j] < 1)
Console.WriteLine("{0} x {1}c", change_given[j], coins[j]*100);
else
Console.WriteLine("{0} x ${1}", change_given[j], coins[j]);
}
答案 1 :(得分:1)
目标:在整数中打印美元和美分。源是一个双打数组。无需更改原始数组本身,只需读取其成员用于显示目的。
请参阅live demo。
预期输出
Change is as follows:
5 cents
10 cents
20 cents
50 cents
1 dollar
1 dollar and 42 cents
2 dollars
<强>代码强>
using System;
public class Test
{
public static void Main()
{
double[] coins = {0.05,0.10,0.20,0.50,1.00,1.42,2.00};
Console.WriteLine("Change is as follows:");
for (int j = 0; j < coins.Length; j++)
{
var amount = coins[j];
var dollars = Math.Floor(amount);
var change = amount - dollars;
var cents = 100*change;
string ds = dollars == 1 ? String.Empty : "s";
string cs = cents == 1 ? String.Empty : "s";
if (amount >= 0 && amount < 1)
{
Console.WriteLine("{0} cents", cents);
}
else if (dollars >= 1 && cents == 0)
{
Console.WriteLine("{0} dollar{1}", dollars, ds);
}
else
{
Console.WriteLine("{0} dollar{1} and {2} cent{3}",
dollars, ds, cents, cs);
}
}
}
}