Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - How to convert 2 restricted decimal variables to a third variable and vice versa?

I have 2 convertor methods as below:

private const decimal MaxValidValue = 99.99m;
public decimal ConvertABToC(decimal a, decimal b)
{
    return a * b;
}

public void ConvertCtoAB(decimal c, ref decimal a, ref decimal b)
{
    if (c > MaxValidValue*MaxValidValue)
    {
        throw new ApplicationException();
    }

    if (c <= MaxValidValue)
    {
        a = 1.00m;
        b = c;
    }
    else 
    {
        // need to introduce some logic or assumptions here
    }
}

There are 3 important things to know:

1) The a and b variables are in the range of 0.00 to 99.99 therefore c can't have a value greater than 99.99*99.99

2) the a, b and c must not have more than 2 decimal precession e.g. a = 99.123 would be invalid.

3) you can use rounding if you'd need to as long as decimal.Round(a * b, 2) == c.

4) combinations like (1, 3), (3, 1), (2, 2), (1, 4), (0.5, 8) or even (0.25, 16) are all valid; it doesn't matter as long as c would be the product of a and b.

How would you complete the implementation of ConvertCtoAB?

Many thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Multiply C by 10,000. Then factor this number into its prime factors. Then find a partition of the prime factors into two sets such that the product of the numbers in each set is less than 10,000. If such a partition can be found, then return these two products divided by 100 as A and B. Otherwise, add one to the number and try again.

For example, if C=100.07, then the factors are 2, 2, 5, 5, 10007. Because one of the products must include the factor 10007, which is a prime number, the first condition can never be satisfied. So we try again with 1000701 = 3*3*3*13*2851. This time, we can partition the number, and we have A=3.51 and B=28.51 as a possible solution.

You can do this at most 99 times. If you need 100 or more, than the input value cannot have been generated from ConvertABToC.

This only guarantees that the result of ConvertCtoAB, when fed back into ConvertABtoC will produce the same C, not the other way around. It appears to violate rule #3, but then elsewhere the question is about rounding.

If no rounding at all is allowed, then one should stop and report infeasibility after trying the original 10000*C.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...