2磅(磅)值之间的差异

时间:2013-08-21 04:59:49

标签: c# c#-4.0 double units-of-measurement

我需要一个建议来找出两磅(磅)值之间的差异。我试过两种方式,

第一种方式,

var pound1 = 151.10;
var pound2 = 142.19;
var finalPoundValue = (pound1 - pound2);

// result 8.91 -> 8 Pounds 91 Ounce 

第二种方式,

var value1 = 151.10;
var value2 = 142.19;
var poundDiff = (151 - 142);
var ounceDiff = (10 - 19);

// result 9 Pounds -9 Ounce

但是,不知道哪一个是找到磅值之间差异的正确方法。或者任何其他可用于解决此问题的最佳方法..?

3 个答案:

答案 0 :(得分:4)

8.91磅 8磅91盎司,而不是远射。它是8磅和(0.91 * 16 = ~15)盎司,因为每磅有16盎司。

我会使用你的第一个变体来获得磅的差异,然后进行一些调整以将其变成磅和盎司,类似于:

var pound1 = 151.10;
var pound2 = 142.19;
var poundDiff = (pound1 - pound2);

var finalPoundValue = (int) poundDiff;
var finalOunceValue = (int) ((poundDiff - finalPoundValue) * 16);

答案 1 :(得分:1)

1 pount = 16盎司。

所以,你必须把数字分成以下几个:假设8.91lb

  1. Pounds = int(8.91)= 8lb

  2. 盎司=(8.91 - int(8.91))* 16 = 14.56

  3. 对两个数字执行相同的操作,然后将磅数加到磅,盎司加到盎司(或减去),然后再进行结转。如果你添加时超过16盎司,你增加1磅,并从盎司减去16。

    这是一个快速回答你的问题。

答案 2 :(得分:1)

如果我经常使用体重,我会创建一个代表体重的课程。该类将权重存储在单个度量单位中,并具有用于获取不同度量单位的只读属性。

class Weight
{
    private double ounces;
    private const double OUNCES_PER_POUND = 16.0;

    public double Pounds
    {
        get { return ounces / OUNCES_PER_POUND; }
    }

    public double Ounces
    {
        get { return ounces; }
    }

    public Weight(double pounds)
    {
        this.ounces = pounds * OUNCES_PER_POUND;
    }

    public Weight(int pounds, double ounces)
    {
        this.ounces = pounds * OUNCES_PER_POUND + ounces;
    }

    // An example operator, probably want to implement addition
    // and perhaps multiplication/division as well
    public static Weight operator -(Weight w1, Weight w2)
    {
        return new Weight((w1.ounces - w2.ounces) / OUNCES_PER_POUND);
    }

    public override string ToString()
    {
        return String.Format("{0} pounds, {1} ounces", (int)Pounds, Math.Round(Ounces % OUNCES_PER_POUND, 4));
    }
}

class Program
{
    public static void Main()
    {
        var w1 = new Weight(151.10);
        var w2 = new Weight(142.19);
        Console.WriteLine("w1: " + w1.ToString() );         // 151 pounds, 1.6 ounces
        Console.WriteLine("w2: " + w2.ToString() );         // 142 pounds, 3.04 ounces
        Console.WriteLine("diff: " + (w1 - w2).ToString()); //   8 pounds, 14.56 ounces
    }
}