Skip to content

Instantly share code, notes, and snippets.

@KotorinChunChun
Last active December 7, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KotorinChunChun/836776dea5affe326ff0f24aef626c7d to your computer and use it in GitHub Desktop.
Save KotorinChunChun/836776dea5affe326ff0f24aef626c7d to your computer and use it in GitHub Desktop.
VBA100本ノック41本目
Option Explicit
Sub knock41()
Dim res As Dictionary: Set res = Quiz四則演算いっぱい出題(99, 20, 3)
Dim msg As Dictionary: Set msg = New Dictionary
Dim key, 正解数
For Each key In res.Keys
正解数 = 正解数 + IIf(res.Item(key), 1, 0)
msg.Add Join(Array( _
IIf(res.Item(key), "○", "×"), _
":", _
key), " "), ""
Next
MsgBox "結果 : " & 正解数 & "/" & res.Count & vbLf & _
Join(msg.Keys, vbLf)
End Sub
' Dictionary("式 = 正解 … 回答") = True/False
Function Quiz四則演算いっぱい出題(最大値1, 最大値2, 出題数) As Dictionary
Set Quiz四則演算いっぱい出題 = New Dictionary
Dim i As Long
For i = 1 To 出題数
Dim res As Dictionary
Set res = Quiz四則演算("" & i & "問目", 最大値1, 最大値2)
Quiz四則演算いっぱい出題.Add res("数式") & " = " & res("正解") & " … " & res("回答"), res("結果")
Next
End Function
' 数式、正解、回答、結果
Function Quiz四則演算(タイトル, 最大値1, 最大値2) As Dictionary
Do
Dim opr: opr = Array("+", "-", "*", "/")(WorksheetFunction.RandBetween(0, 3))
Dim num1: num1 = WorksheetFunction.RandBetween(1, 最大値1)
Dim num2: num2 = WorksheetFunction.RandBetween(1, 最大値2)
Dim expr: expr = Join(Array(num1, opr, num2), " ")
'難易度調整
' 掛け算は1x2桁か、2x1桁に
' 割り算は割り切れるように
Select Case opr
Case "+", "-": Exit Do
Case "*": If Len(num1 & num2) <= 3 Then Exit Do
Case "/": If num1 >= num2 And num1 \ num2 = 0 Then Exit Do
End Select
Loop
Dim res: res = InputBox(タイトル & vbLf & expr, "答えは?")
Set Quiz四則演算 = New Dictionary
Quiz四則演算.Add "数式", expr
Quiz四則演算.Add "正解", SafeEvaluate(expr)
If res = "" Or Not IsNumeric(res) Then
Quiz四則演算.Add "回答", "無回答"
Quiz四則演算.Add "結果", False
Else
Quiz四則演算.Add "回答", res
Quiz四則演算.Add "結果", SafeEvaluate(expr & "=" & res)
End If
End Function
Function SafeEvaluate(expr) As Variant
On Error Resume Next
SafeEvaluate = Evaluate(expr)
End Function
@KotorinChunChun
Copy link
Author

Twitter お題

#VBA100本ノック 41本目
暗算練習アプリを作成します。
・整数2個と+-*/の演算子をランダムに選ぶ
・問題をInputBoxに表示
・入力値を採点
・全10問、最後に10点満点で点数をMsgBox表示
・キャンセルや未回答は次の問題に進む
※整数の範囲については暗算できる範囲で随意
※添付GIFを参考に

https://twitter.com/yamaoka_ss/status/1335810354249564160?s=20

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment