Calculate Percentage in Java – 在Java中计算百分比

最后修改: 2018年 9月 30日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this quick tutorial, we’re going to implement a CLI program to calculate percentage in Java.

在这个快速教程中,我们将实现一个CLI程序来计算Java中的百分比。

But first, let’s define how to calculate percentage mathematically.

但首先,让我们定义一下如何在数学上计算百分比。

2. Mathematical Formula

2.数学公式

In mathematics, a percentage is a number or ratio expressed as a fraction of 100. It’s often denoted using the percent sign, “%”.

在数学中,百分比是一个以100的分数表示的数字或比率。它通常用百分号”%”来表示。

Let’s consider a student that obtains x marks out of total y marks. The formula to calculate percentage marks obtained by that student would be:

让我们考虑一个学生在总分Y中获得了X分。计算该学生获得的分数百分比的公式是:。

percentage = (x/y)*100

百分比=(x/y)*100

3. Java Program

3.爪哇程序

Now that we are clear on how to calculate percentage mathematically, let’s build a program in Java to calculate it:

现在我们清楚了如何在数学上计算百分比,让我们用Java建立一个程序来计算它。

public class PercentageCalculator {

    public double calculatePercentage(double obtained, double total) {
        return obtained * 100 / total;
    }

    public static void main(String[] args) {
        PercentageCalculator pc = new PercentageCalculator();
        Scanner in = new Scanner(System.in);
        System.out.println("Enter obtained marks:");
        double obtained = in.nextDouble();
        System.out.println("Enter total marks:");
        double total = in.nextDouble();
        System.out.println(
          "Percentage obtained: " + pc.calculatePercentage(obtained, total));
    }
}

This program takes the marks of the student (obtained marks and total marks) from CLI and then calls calculatePercentage() method to calculate the percentage out of it.

这个程序从CLI获取学生的分数(获得的分数和总分),然后调用calculatePercentage()方法来计算出百分比。

Here we’ve chosen double as a data type for input and output as it could store decimal numbers with up to 16 digits of precision. Hence, it should be adequate for our use case.

在这里,我们选择double作为输入和输出的数据类型,因为它可以存储精度高达16位的十进制数字。因此,对于我们的用例来说,它应该是足够的。

4. Output

4.输出

Let’s run this program and see the result:

让我们运行这个程序,看看结果。

Enter obtained marks:
87
Enter total marks:
100
Percentage obtained: 87.0

Process finished with exit code 0

5. Conclusion

5.总结

In this article, we took a look at how to calculate percentage mathematically and then wrote a Java CLI program to calculate it.

在这篇文章中,我们看了一下如何从数学上计算百分比,然后写了一个Java CLI程序来计算它。

Finally, as always, the code used in the example is available over on GitHub.

最后,像往常一样,例子中使用的代码可以在GitHub上找到