简体   繁体   English

我对 java 的百分比变化有疑问

[英]I have a question about percentage change in java

I need to find the percentage change of different numbers, I've got the formula down but the result keep ending up being minus instead of a positive eg 100 to 150 comes out a -50.00% instead of 50.00%.我需要找到不同数字的百分比变化,我已经把公式记下来了,但结果一直是负数而不是正数,例如 100 到 150 的结果是 -50.00% 而不是 50.00%。 Thanks in advance!提前致谢!

package package2;
import java.util.Scanner;

class Selection3 {

public static void main (String [] args)
{

    perChange();

    
}


public static void perChange() {
    double perCha0, perCha1, perCha2, perCha3, perCha4, perCha5;


    perCha0 = ((38 - 108)*100/38);
    perCha1 = ((35 - 63)*100/35);
    perCha2 = ((4 - 6)*100/4);
    perCha3 = ((3 - 5)*100/3);
    perCha4 = ((20 - 40)*100/20);
    perCha5 = ((100 - 150)*100/100);
    
    System.out.println(perCha0);
    System.out.println(perCha1);
    System.out.println(perCha2);
    System.out.println(perCha3);
    System.out.println(perCha4);
    System.out.println(perCha5);
    
}

output output

-184.0 -80.0 -50.0 -66.0 -100.0 -50.0 -184.0 -80.0 -50.0 -66.0 -100.0 -50.0

The problem you have is a math problem, and you have encoded a bad formula into your programming.您遇到的问题是数学问题,并且您在编程中编码了一个错误的公式。

A percentage of change is a "difference of change" divided by the original amount.变化百分比是“变化差异”除以原始数量。 When 30 items become 60 items, it is a difference of +30;当30项变成60项时,相差+30; but, because you subtract the numbers in the wrong order, you get an incorrect "difference" of -30.但是,因为你以错误的顺序减去数字,你得到一个不正确的“差”-30。

Subtracting is not like addition, changing the order of the numbers doesn't result in the same result.减法不像加法,改变数字的顺序不会产生相同的结果。

You have a math problem.你有一道数学题。 For example in you first formula: 38 * 100 / 108 = 35.15%例如在你的第一个公式中:38 * 100 / 108 = 35.15%

You have basically 3 options:你基本上有3个选择:

  1. Use Math.abs()使用 Math.abs()

     perCha0 = (Math.abs(38 - 108)*100/38); // or perCha0 = (Math.abs(x1 - x2)*100/x1);
  2. If else condition If else 条件

     if(x2 > x1) perCha0 = ((x2 - x1)*100/x1); else perCha0 = ((x1 - x2)*100/x1);
  3. If you know before that you are calculating for percentage increase ie x2 > x1如果您之前知道您正在计算百分比增加,即 x2 > x1

     perCha0 = ((x2 - x1)*100/x1);

You can also simplify the above if you want.如果需要,您还可以简化上述内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM