How to simplify fractions?

前端 未结 4 585
时光取名叫无心
时光取名叫无心 2021-01-13 02:05

How to simplify a fraction in C#? For example, given 1 11/6, I need it simplified to 2 5/6.

4条回答
  •  梦谈多话
    2021-01-13 02:33

    int unit = 1;
    int numerator = 11;
    int denominator = 6;
    
    while(numerator >= denominator)
    {
        numerator -= denominator;
        if(unit < 0)
            unit--;
        else
            unit++;
    }
    

    Then do whatever you like with the variables.

    Note that this isn't particularly general.... in particular I doubt it's going to play well with negative numbers (edit: might be better now)

提交回复
热议问题