0

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

第一种方式,

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

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

4

3 回答 3

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);
于 2013-08-21T05:05:36.073 回答
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
    }
}
于 2013-08-21T05:34:16.727 回答
1

1 磅 = 16 盎司。

因此,您必须将数字分为以下几部分:假设 8.91lb

  1. 磅 = int(8.91) = 8lb

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

对这两个数字做同样的事情,然后将磅加到磅,将盎司加到盎司(或减去),然后进行结转。如果添加时超过 16 盎司,则增加 1 磅,并从盎司中减去 16。

这是一个供您查看的快速答案。

于 2013-08-21T05:07:04.633 回答