第9講 For文以外の様々なループ文

第6話 合計上限値を超えない和の計算

第5話の最後に示したコードではだめであるな理由を説明しましょう。
はじめの値1
合計上限値100
変化の幅1
の場合で考えます。
1+2+3+・・・+13=91です。
'1乗の和の計算
Sub f1(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do While
w < o
    w = w + i
    i = i + b
  Loop

  Cells(9, 4) = w

End Sub
これはまだ、
w < oを満たしていますから、次の計算
91+14が行われてしまいます。
したがって、和は105になって100を超えてしまいます。
だから、条件式では次の14を加えたときに、超えないかを判断しなければなりませんので、
w + i <= oとしなければなりません。

While文による解答例
Private Sub CommandButton1_Click()

  Dim h As Long, o As Long, b As Long

  h = Cells(5, 2)
  o = Cells(6, 2)
  b = Cells(7, 2)
  f1 h, o, b '1乗の和の計算
  f2 h, o, b '2乗の和の計算
  f3 h, o, b '3乗の和の計算
  f4 h, o, b '4乗の和の計算

End Sub

'1乗の和の計算
Sub f1(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  While w + i <= o
    w = w + i
    i = i + b
  Wend

  Cells(9, 4) = w

End Sub

'2乗の和の計算
Sub f2(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  While
w + i * i <= o
    w = w + i * i
    i = i + b
  Wend

  Cells(10, 4) = w

End Sub

'3乗の和の計算
Sub f3(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  While
w +i * i * i <= o
    w = w + i * i * i
    i = i + b
  Wend

  Cells(11, 4) = w

End Sub

'4乗の和の計算
Sub f4(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  While
w + i * i * i * i <= o
    w = w + i * i * i * i
    i = i + b
  Wend

  Cells(12, 4) = w

End Sub

Private Sub CommandButton2_Click()

  Range("B5:B7,D9:D13").Select
  Selection.ClearContents
  Cells(1, 1).Select

End Sub



Do...Loop Until文による解答例
Private Sub CommandButton1_Click()

  Dim h As Long, o As Long, b As Long

  h = Cells(5, 2)
  o = Cells(6, 2)
  b = Cells(7, 2)
  f1 h, o, b '1乗の和の計算
  f2 h, o, b '2乗の和の計算
  f3 h, o, b '3乗の和の計算
  f4 h, o, b '4乗の和の計算

End Sub

'1乗の和の計算
Sub f1(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do
    w = w + i
    i = i + b
  Loop Until
w + i > o

  Cells(9, 4) = w

End Sub

'2乗の和の計算
Sub f2(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do
    w = w + i * i
    i = i + b
  Loop Until
w + i * i > o

  Cells(10, 4) = w

End Sub

'3乗の和の計算
Sub f3(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do
    w = w + i * i * i
    i = i + b
  Loop Until
w + i * i * i > o

  Cells(11, 4) = w

End Sub

'4乗の和の計算
Sub f4(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do
    w = w + i * i * i * i
    i = i + b
  Loop Until
w + i * i * i * i> o

  Cells(12, 4) = w

End Sub

Do While...Loop文、Do...While Loop文、Do Until...Loop文については解答例を省略させていただきます。

次話では、While文とFor文の関係を考えてみたいと思いますので、
合計上限値を超えない範囲で和を計算させるという課題をFor文で成就させましょう。


第5話へ 第7話へ

004


vc++講義へ
vb講義へ
VB講義基礎へ
初心者のための世界で一番わかりやすいVisual C++入門基礎講座へ
初心者のための世界で一番わかりやすいVisual Basic入門基礎講座へ

数学研究室に戻る