此代码找不到正确的输出
表示n = 1(虽然它给出了n = 2,3,4..etc的正确输出。)
如果我们把n = 1来找到x那么i循环将从1继续到0,因此x中的第一项应该消失,剩下的应该是第二项5;但它给0?
运行for循环的输入n是否有任何限制?我将不胜感激。
Function math(n As Integer) As Double
Dim i As Integer
Dim x As Double
For i = 1 To n - 1
x = (n - 1) * 2 + 5
sum = sum + x
Next i
math = sum
End Function
答案 0 :(得分:2)
为什么不简单:
Math = (n * 2 + 3) * Abs((n - 1) - (n = 1))
???
如果答案是正确的,那么@font-face {
font-family: 'Glyphicons Halflings';
src: url('glyphicons-halflings-regular.eot');
src: url('glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
url('glyphicons-halflings-regular.woff') format('woff'),
url('glyphicons-halflings-regular.ttf') format('truetype'),
url('glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
会更容易理解并且更有意义
答案 1 :(得分:1)
如果n = 1
,您的For i = 1 To 0
结果不正确
应表达For i = 1 To 0 STEP -1
。
所以我建议你添加STEP BY
,并确保它是1到-1,具体取决于N。
答案 2 :(得分:1)
在for循环中,如果你不精确Step
,变量只会递增1。
在这里,你从1开始转到0,所以循环不会执行,你需要测试n来涵盖这两种情况:
Function math(n As Integer) As Double
If n < 0 Then Exit Function
Dim i As Integer
Dim x As Double
Dim Summ As Double
Select Case n
Case Is > 1
For i = 1 To n - 1
x = (i - 1) * 2 + 5
Summ = Summ + x
Next i
Case Is = 1
Summ = (n - 1) * 2 + 5
Case Is = 0
Summ = 5
Case Else
MsgBox "This case is not supported", vbInformation + vbOKOnly
Exit Function
End Select
math = Summ
End Function