Java算术运算百分比 [英] Java arithmetics for calculating a percentage

查看:445
本文介绍了Java算术运算百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java应用程序中有一个小问题.

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(int questions, int correct){
    Float x = new Float(questions);
    Float y = new Float(correct);

    Float num = (float) (100 / questions * correct);
    return num;
}

但是,当我有38个问题并且38个正确时,它会显示76.

However, when I have 38 questions and 38 are correct it displays 76.

推荐答案

首先,您不应该在所有地方都使用Float-您需要float;不需要在这里拳击.

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

第二,您根本不使用xy.

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

第三,我要说的是,您表达方程式的方式至少是令人困惑的. 可能,只需更改为xy就可以了,但是我不会-我会改变您表达自己的整个方式.

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.

第四,您通过在PascalCase中编写方法名称来违反Java命名约定.您还遇到了拼写错误.

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;

...但是您需要知道优先级规则才能对其进行验证.我已经明确包含了两个强制类型转换,以明确表示我想将每个操作数转换为float 之前的行.

... 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.

这篇关于Java算术运算百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆