Last active
December 7, 2020 16:13
-
-
Save KotorinChunChun/836776dea5affe326ff0f24aef626c7d to your computer and use it in GitHub Desktop.
VBA100本ノック41本目
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Twitter お題
https://twitter.com/yamaoka_ss/status/1335810354249564160?s=20