How to keep ratio in one variable and read it in C #

Let's say I have a system that should store how many people voted on fighter A and how many on fighter B.

Let's say the ratio is 200: 1

How to save this value in one variable instead of saving both values ​​(number of voters on A and number of voters on B) with two variables.

How do you do this?

+3
source share
7 answers

Given that the question is formulated, this may 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);
}
+11

, , . double:

double ratio = (double)a/b;
+4

string ratio = "200: 1";//simple:)

+4

struct :

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;
    }
}

, . , , , . , GCD-.

+3

, string

string s=string.Format("{0}:{1}", 3, 5);
+1

an array? int[] ratio = new int[2]much thinner than the whole structure / class for 2 variables. Although, if you want to add helper methods to it, structure is the way to go.

+1
source

In my opinion, you can use doubles.

Relationship Number

1: 200 1.200

200: 1 200: 1

0: 1 0.1

1: 0 1.0

0: 0 0.0

It is easy to use.

firstNumber = (int)Number;
secondNumber = Number - firstNumber;
0
source

Source: https://habr.com/ru/post/1765592/


All Articles