VB點樣用for....next 計開方?(20分)

2007-05-04 6:40 am
write a function summarion() to calculate the sum of

sum = 1+開方3+開方5+開方7+開方9

use for...next to complete the program.The sum as double

同埋我想知道...點用DO UNTIL 做番上面條問題...?
thx!

回答 (3)

2007-05-04 11:41 am
✔ 最佳答案
用 For Loop 比較好,計算平方根可以用 VB 的 Sqr() Function.

Function summarion(ByVal count As Integer) As Double

Dim i As Integer
Dim loopCount As Integer
Dim total As Double

loopCount = count * 2
For i = 2 To loopCount Step 2
total = total + Sqr(-1 + i)

' 不用 Sqr() 的寫法
' total = total + (-1 + i) ^ 0.5
Next
summarion = total
End Function

Do Util 的寫法

Function summarion(ByVal count As Integer) As Double
Dim i As Integer
Dim loopCount As Integer
Dim total As Double

i = 2
Do Until loopCount >= count
total = total + Sqr(-1 + i)
i = i + 2
loopCount = loopCount + 1
Loop
summarion = total
End Function

2007-05-05 02:00:44 補充:
答新田美香 你的方法很直接,但是有一要點注意要計 sum = 1+開方3+開方5+開方7+開方9count 是 10, 不是 5.如果要計 sum = 1+開方4+開方7+開方10+開方13count 就是 15所以 count 應該是 function 內的變數, 不應是 funtion argument

2007-05-05 02:05:59 補充:
可以改成Function summarion(ByVal count As Integer, ByVal stepx As Integer) As DoubleFor i = 1 To count * stepx' code herenextEnd function
2007-05-04 11:06 pm
可能是每人對題目的理解不同, 樓上兩位與我的答案都各不相同
我的理解: 由1開始 至 count, 步長是2, 求各數的開方和
Function summarion(count As Integer) As Double
Dim i As Integer
Dim X As Double
For i = 1 To count
If i Mod 2 = 1 Then X = X + i ^ 0.5
Next i
summarion = X
End Function

如用 Do Until:
Do Until i = count
i = i + 1
If i Mod 2 = 1 Then X = X + i ^ 0.5
Loop

我另有建議, 在Function 加多1個叫stepx的引數, 代表步長, Function的應用性會更大
stepx = 1, 各數是 {1,2,3,4,5,6…count}
stepx = 2, 各數是 {1,3,5,7,9,11…count)
stepx = 3, 各數是 {1,4,7,10,13,16…count)
如此類推。
Function summarion(count As Integer, stepx As Integer) As Double
Dim i As Integer
Dim X As Double
For i = 1 To count
If i Mod stepx = 1 Or stepx = 1 Then X = X + i ^ 0.5
Next i
summarion = X
End Function
2007-05-04 7:24 am
function summarion(count as integer) as double
dim i as integer
dim dblresult as double
for i = 1 to count
dblresult = dblresult + i ^ 0.5
next
summarion=dblresult
end function
function summarion(count as integer) as double ' use do until
dim i as integer
dim dblresult as double
i=1
do
if i<=count then
dblresult = dblresult + i ^ 0.5
end if
i=i+1
loop until i>count or count<=0
summarion=dblresult
end function

2007-05-04 12:30:48 補充:
更正: dblresult = dblresult (i*2-1) ^ 0.5
參考: me


收錄日期: 2021-04-26 13:13:02
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070503000051KK04715

檢視 Wayback Machine 備份