【问题标题】:C# - Get X percent of Y dynamicallyC# - 动态获取 Y 的 X 百分比
【发布时间】:2022-10-14 22:12:34
【问题描述】:

我试图计算 Y 的 X%,尽管我得到的结果好坏参半。

我尝试了以下等式:

return (percent / i) * 100; // Gives 0 for 200.GetPercent(10)
return percent * 100 / i; // Gives 5 for 200.GetPercent(10)

对于方法:

public static int GetPercent(this int i, int percent)
{
    return percent * 100 / i;
}

但是没有人给我 20 回 200.GetPercent(10)

【问题讨论】:

  • 提示:如果 X 上升或者Y上升,结果应该上升,对吧?所以你不应该划分由他们中的任何一个。这不是一个真正的编码问题——它只是数学问题。一旦你完成了数学运算,代码将非常简单,一个棘手的方面是你正在使用整数算术。
  • return (i * percent) / 100;
  • 对了,你试过了吗?它做你想做的事吗?对于像“15% of 10”这样的事情,你想发生什么?

标签: c#


【解决方案1】:

我相信这是正确的公式:Y * X / 100

public static int GetPercent(this int i, int percent)
{
    return (i * percent) / 100;
}

【讨论】:

  • 数学现在是正确的,但您确定要返回一个整数吗?使用您当前的代码,3.GetPercent(50) 将返回 1。
【解决方案2】:

使用浮点类型更好地处理百分比,这里是使用双精度和另一个参数来设置精度的版本

public static double GetPercent(this int i, int percent, int precision) => 
    Math.Round(((i * percent) / 100), precision);

您还可以将精度定义为 optional parameter,以使用 int precision = n 为其提供默认值(n 是您选择的 int)

public static double GetPercent(this int i, int percent, int precision = 2) => 
    Math.Round(((i * percent) / 100), precision);

200.GetPercent(10, 4); //precision = 4
200.GetPercent(10); //precision defaults to = 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多