Java arithmetics for calculating a percentage

后端 未结 8 693
一个人的身影
一个人的身影 2021-01-21 14:00

I have a little problem in my java application.

I have to calculate the score they have when they finish, I use this method:

public Float ScoreProcent(in         


        
8条回答
  •  情歌与酒
    2021-01-21 14:20

    Firstly, you shouldn't be using Float all over the place - you want float; there's no need to be boxing here.

    Secondly, you're not using x and y at all.

    Thirdly, I'd say the way you're expressing the equation is at the least confusing. It's possible that just changing to x and y would be fine, but I wouldn't - I'd change the whole way you're expressing yourself.

    Fourthly, you're violating Java naming conventions by writing a method name in PascalCase. You've also got a spelling mistake.

    Fixing all of these, you'd end with with something like:

    public static float getPercentageCorrect(int questions, int correct) {
        float proportionCorrect = ((float) correct) / ((float) questions);
        return proportionCorrect * 100;
    }
    

    I'd actually generalize this - it's not specific to "correct answers", so can be used for anything where it's some score out of a total:

    /**
     * Returns a proportion (n out of a total) as a percentage, in a float.
     */
    public static float getPercentage(int n, int total) {
        float proportion = ((float) n) / ((float) total);
        return proportion * 100;
    }
    

    As noted in comments, this could be written as:

    float proportion = (float) n / total;
    

    ... but then you need to know the precedence rules to validate it. I've included both casts explicitly to make it clear that I want to convert each operand to float before the division.

提交回复
热议问题