我对 java 的百分比变化有疑问
I have a question about percentage change in java
我需要找到不同数字的百分比变化,我已经记下了公式,但结果总是以负数而不是正数结束,例如100 到 150 的结果是 -50.00% 而不是 50.00%。提前致谢!
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);
}
输出
-184.0
-80.0
-50.0
-66.0
-100.0
-50.0
你遇到的问题是一道数学题,你在程序中编码了一个错误的公式。
变化百分比是“变化的差异”除以原始量。当30件变成60件时,相差+30;但是,因为你以错误的顺序减去数字,你得到一个不正确的 -30 的“差异”。
减法不同于加法,改变数字的顺序不会产生相同的结果。
你有一道数学题。例如在你的第一个公式中:
38 * 100 / 108 = 35.15%
你基本上有 3 个选择:
使用Math.abs()
perCha0 = (Math.abs(38 - 108)*100/38);
// or
perCha0 = (Math.abs(x1 - x2)*100/x1);
If else条件
if(x2 > x1)
perCha0 = ((x2 - x1)*100/x1);
else
perCha0 = ((x1 - x2)*100/x1);
如果您之前知道您正在计算百分比增加,即 x2 > x1
perCha0 = ((x2 - x1)*100/x1);
如果你愿意,你也可以简化上面的内容。
我需要找到不同数字的百分比变化,我已经记下了公式,但结果总是以负数而不是正数结束,例如100 到 150 的结果是 -50.00% 而不是 50.00%。提前致谢!
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);
}
输出
-184.0 -80.0 -50.0 -66.0 -100.0 -50.0
你遇到的问题是一道数学题,你在程序中编码了一个错误的公式。
变化百分比是“变化的差异”除以原始量。当30件变成60件时,相差+30;但是,因为你以错误的顺序减去数字,你得到一个不正确的 -30 的“差异”。
减法不同于加法,改变数字的顺序不会产生相同的结果。
你有一道数学题。例如在你的第一个公式中: 38 * 100 / 108 = 35.15%
你基本上有 3 个选择:
使用Math.abs()
perCha0 = (Math.abs(38 - 108)*100/38); // or perCha0 = (Math.abs(x1 - x2)*100/x1);
If else条件
if(x2 > x1) perCha0 = ((x2 - x1)*100/x1); else perCha0 = ((x1 - x2)*100/x1);
如果您之前知道您正在计算百分比增加,即 x2 > x1
perCha0 = ((x2 - x1)*100/x1);
如果你愿意,你也可以简化上面的内容。