How to store a ratio in a single variable and read it back in C#
Let's say I have a system that must store how many people voted on fighter A and how many on fighter B.
Let's say ratio is 200:1
How can I store开发者_如何学JAVA that value in a single variable, instead of storing both values (number of voters on A and number of voters on B) in two variables.
How you would do that?
From the way that the question is worded this might not be the answer you are looking for, but the easiest way is to use a struct:
struct Ratio
{
public Ratio(int a, int b)
{
this.a = a;
this.b = b;
}
public int a = 1;
public int b = 1;
}
You will almost certainly want to use properties instead of fields and you will probably also want to overload ==
and !=
, something like:
public static bool operator ==(Ratio x, Ratio y)
{
if (x.b == 0 || y.b == 0)
return x.a == y.a;
// There is some debate on the most efficient / accurate way of doing the following
// (see the comments), however you get the idea! :-)
return (x.a * y.b) == (x.b / y.a);
}
public static bool operator !=(Ratio x, Ratio y)
{
return !(x == y);
}
public override string ToString()
{
return string.Format("{0}:{1}", this.a, this.b);
}
A ratio is, by definition, the result of dividing two numbers. Therefore, just do that division and store the result in a double
:
double ratio = (double)a/b;
string ratio="200:1"; // simple :)
You can use struct like this:
struct Ratio
{
public void VoteA()
{
A++;
}
public void VoteB()
{
B++;
}
public int A { get; private set; }
public int B { get; private set; }
public override string ToString()
{
return A + ":" + B;
}
}
It's enough to implement voting in case if you have only two options available. Otherwise you should implement constructor accepting number of options, data structure to store number of votes, methods for voting or index operator. If you need the ratio for some integral math applications you might want to implement GCD method.
It think you need to do it in a string
for a single variable
string s=string.Format("{0}:{1}", 3, 5);
Array? int[] ratio = new int[2]
is much slimmer than a whole struct/class for 2 variables. Though if you want to add helper methods to it, a struct is the way to go.
In my opinion you can use doubles.
Ratio Number
1:200 1.200
200:1 200:1
0:1 0.1
1:0 1.0
0:0 0.0
It's easy to use.
firstNumber = (int)Number;
secondNumber = Number - firstNumber;
精彩评论