计算在C#中的比例 [英] Calculate a Ratio in C#

查看:339
本文介绍了计算在C#中的比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这将是简单的,但谷歌搜索似乎并没有帮助。

基本上,我试图写它会返回一个比一个字符串的函数(如4:3)当两个整数(如800和600)电源

 字符串GetRatio(int类型的,整数B){
    // code我在寻找
    回报率;
}


解决方案

我没有一个现成的code,但它应该是相当简单的。也就是说,确定 GCD 并使用它:

  VAR GCD = GCD(A,B);
返回的String.Format({0}:{1},A / GCD,B / GCD)

和计算GCD,使用一个非常基本的功能欧几里德算法

 静态INT GCD(INT A,INT B){
    返回b == 0?答:GCD(B,A%B);
}

I thought this would be simple, but searching Google didn't seem to help.

I'm basically trying to write a function which will return a ratio as a string (eg 4:3) when supplies with two integers (eg 800 and 600).

string GetRatio(Int A, Int B) {
    // Code I'm looking for
    return Ratio;
}

解决方案

I don't have a ready made code but it should be fairly simple. Namely, determine the GCD and work with it:

var gcd = GCD(A, B);
return string.Format("{0}:{1}", A / gcd, B / gcd)

And a very basic function for calculating the GCD, using the Euclidean algorithm:

static int GCD(int a, int b) {
    return b == 0 ? a : GCD(b, a % b);
}

这篇关于计算在C#中的比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆