我们学校的等级等级从1.10到1小数点。如果你什么也不做,你的分数仍然是1.0。及格的分数等于5.5。“cesuur”百分比定义了给学生的5.5正确答案的百分比。
示例:
问题:我如何简化代码?我怎样才能使它更健壮呢?
Public Function Grade(Points As Integer, MaxPoints As Integer, Cesuur As Double) As Double
Dim passPoints As Integer
Dim maxGrade As Integer
Dim minGrade As Integer
Dim passGrade As Double
Dim base As Double
Dim restPoints As Integer
Dim restPass As Double
passPoints = Cesuur * MaxPoints
maxGrade = 10
minGrade = 1
passGrade = (maxGrade + minGrade) / 2
base = maxGrade - passGrade
If Points < passPoints Then
Grade = 1 + (passGrade - minGrade) * Points / passPoints
Else
restPoints = MaxPoints - Points
restPass = MaxPoints * (1 - Cesuur)
Grade = maxGrade - restPoints * base / restPass
End If
Grade = Round(Grade, 1)
End Function发布于 2015-05-21 14:20:07
函数的参数是通过引用隐式传递的,这可能不是目的,因为没有一个参数被分配/返回给调用者。
签名应该按值传递其参数,如下所示:
Public Function Grade(ByVal Points As Integer, ByVal MaxByVal As Integer, ByVal Cesuur As Double) As DoublemaxGrade和minGrade只分配一次--它们本质上是常量,可以这样声明:
Const MAXGRADE As Integer = 10
Const MINGRADE As Integer = 1我建议将变量声明得更接近它们的用法,并且可能只在一个地方分配函数的返回值。
变量restPoints和restPass只在Else块中与及格等级一起使用。VBA不会在任何比过程作用域更紧的范围内对变量进行范围调整,因此您可以提取一种计算通过级别的方法,但这是边缘过头--下面是将参数大小写设置为camelCase的样子:
Option Explicit
Private Const MAXGRADE As Integer = 10
Private Const MINGRADE As Integer = 1
Public Function Grade(ByVal points As Integer, ByVal maxPoints As Integer, ByVal cesuur As Double) As Double
Dim passPoints As Integer
passPoints = cesuur * maxPoints
Dim passGrade As Double
passGrade = (MAXGRADE + MINGRADE) / 2
Dim base As Double
base = MAXGRADE - passGrade
Dim result As Double
If points < passPoints Then
result = 1 + (passGrade - MINGRADE) * points / passPoints
Else
result = CalculatePassingGrade(MAXGRADE, base, points, maxPoints, cesuur)
End If
Grade = Round(result, 1)
End Function
Private Function CalculatePassingGrade(ByVal base As Double, ByVal points As Integer, ByVal maxPoints As Integer, ByVal cesuur As Double) As Double
Dim restPoints As Integer
restPoints = maxPoints - points
Dim restPass As Double
restPass = mxPoints * (1 - cesuur)
CalculatePassingGrade = MAXGRADE - restPoints * base / restPass
End Function发布于 2015-05-21 14:19:02
就在这里
如果分数< passPoints,则等级=1+ (passGrade - minGrade) *记分/ passPoints passPoints restPoints = MaxPoints -记分restPass = MaxPoints *(1-Cesuur)等级= maxGrade - restPoints * base / restPass结束
在这两个街区中,你都有复杂的数学方程式,只要读一读,我就可以采取几种方法。
年级=1+ (passGrade - minGrade) *分/ passPoints
年级应该是
(1 + (passGrade - minGrade) * Points) / passPoints或
(1 + (passGrade - minGrade)) * (Points / passPoints)或
(1 + ((passGrade - minGrade) * Points)) / passPoints在这两个复杂方程中,你应该更清楚地说明这一点。
您也不需要检查passPoints或restPass是否为零,如果Cesuur或MaxPoints为零,那么代码就会崩溃。
我知道你并不是真的要用一个零来得到一个最大值或者百分比,但是这是一个函数,它只做它告诉它的事情,所以你应该确保一些东西没有告诉它做错了什么。
参数的命名是PascalCase而不是camelCase,这是不标准的。
https://codereview.stackexchange.com/questions/91402
复制相似问题