【问题标题】:How to find the percentage within a given range in java [closed]如何在java中找到给定范围内的百分比[关闭]
【发布时间】:2014-03-19 06:44:04
【问题描述】:

我有一个从“min”到“max”的给定范围。最小值表示为 100%,最大值表示为 0%。平均值 (min+max)/2 表示为 50%。

我将给出的输入是 [min, max] 范围内的值“x”,输出应该是与提供的输入相对应的百分比。

例如,将范围视为 [100, 300]

if x=100 then output=100%
if x=300 then output=0%
if x=200 then output=50%
if x=150 then output=75%
if x=250 then output=25%

无论在 [min, max] 范围内提供的 x 值如何,都应计算相应的百分比。

我尝试了各种逻辑,但我似乎无法为这个问题找到正确的公式。

【问题讨论】:

  • 这个问题似乎是题外话,因为它是关于为问题找到正确的公式。它可能是math.stackexchange.com 的主题
  • 从值和最大值中减去最小值,然后正常计算百分比...
  • @devnull 好的,我会检查一下..谢谢 :)
  • @MadProgrammer 我听不懂你在说什么......你能解释一下吗?

标签: java excel math numbers formula


【解决方案1】:

如果 start 和 end 是存储值的变量,则

1) 你可以从 0 开始限制到 end-start 和值传递值 - 开始 2) 计算百分比 3) 100%回报

public static void main(String[] args) {

    System.out.println(find_percent(100,300,100)+"%");
    System.out.println(find_percent(100,300,300)+"%");
    System.out.println(find_percent(100,300,200)+"%");
    System.out.println(find_percent(100,300,150)+"%");
    System.out.println(find_percent(100,300,250)+"%");
    System.out.println("");
    System.out.println(find_percent(20,40,20)+"%");
    System.out.println(find_percent(20,40,40)+"%");
    System.out.println(find_percent(20,40,25)+"%");
    System.out.println(find_percent(20,40,35)+"%");

}


public static double find_percent(double start,double end,double val){

    end = end- start;
    val = val - start;
    start = 0;

    return((1-(val/end))*100);
}

输出:

100.0%
0.0%
50.0%
75.0%
25.0%

100.0%
0.0%
75.0%
25.0%

【讨论】:

  • 效果很好,兄弟 :) 非常感谢你..我已经尝试了所有可能的范围和输入值“x”它的工作很好..
【解决方案2】:

在 Java 中,对应的赋值是

double percentage = 1.0f - Math.Abs(x-min)/Math.Abs(max-min);

其中绝对函数用于覆盖maxmin符号不同的情况。

【讨论】:

  • 但如果我在此处给出 x=200 的值,范围为 [100,300],则结果为 100%。实际上应该是 50%..
  • 如果将值 x=200min=100max=300 插入到上面的表达式中,则计算得到 (x-min)/(max-min)=(200-100)/(300-100)=100/200=50%,这就是所需的结果。
  • 嗯,我明白了..它很好,那么我也可以使用它:)
  • 是的,它现在可以工作了 :) 这提供了与@Jay Solanki 提到的答案相同的结果。这里它给出了从 0 到 1 的值,前者提供了从 0 到 100% 的百分比结果。
猜你喜欢
  • 2021-05-05
  • 2021-02-18
  • 2022-12-18
  • 1970-01-01
  • 2012-11-02
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多