vb解决鸡兔同笼问题
窗体设计可以按照我的截图!控件就不说了!很简单!添加控件后直接把代码复制进去就行了!
代码如下:'判断数据是否是整数!
Public Function isInt(s As String) As Boolean
If CStr(CInt(Val(s))) = s Then
isInt = True
Else
isInt = False
End If
End Function
'根据头数和脚数求解兔子的数量的方程
Public Function Solv(head As Integer, foot As Integer) As Integer
Dim Rabit As Integer
Rabit = (foot - head * 2) / 2
Solv = Rabit
End Function
Private Sub Command1_Click()
Dim err As String, OK As String
Dim h_num As Integer, f_num As Integer
If isInt(Text1.Text) Then
h_num = CInt(Text1.Text)
Else
err = err + "头数不是正整数!"
End If
If isInt(Text2.Text) Then
f_num = CInt(Text2.Text)
Else
err = err + "脚数不是正整数!"
End If
If err = "" Then
OK = OK & "兔子数量为:" & CStr(Solv(h_num, f_num)) & vbCrLf
OK = OK & "鸡的数量为:" & CStr(h_num - Solv(h_num, f_num)) & vbCrLf
MsgBox OK, vbOKOnly, "结果显示"
Else
MsgBox err, vbOKOnly, "出错了"
End If
End Sub
'鸡有两只脚,兔有四只脚。已知鸡和兔的总头数是H,总脚数是F
H = Val(InputBox("请输入总头数"))
F = Val(InputBox("请输入总脚数"))
t = (F - 2 * H) / 2
j = H - t
Print "鸡有"; j; "只,兔有"; t; "只"
End Sub
则脚数:二分之一F只
鸡,加回原来的脚:六分之一H只*2=三分之一H只
兔,不是兔就是鸡:单位“1”H-三分之一H=三分之二H
则,鸡有三分之一H只,
兔有三分之二H只。
(我是六年级小学生,思想很简单,只能想到这个了。。)
JJ=H-TT
要先对数据判断,如F必为偶数,F>=2*H
F=2*j+4*t
H=j+t
只要满足这个方程就可以了。可以用循坏来遍历。
dim j,t
dim retJ,retT
for j=1 to H
for t=1 to H
if F=2*j+4*t and H=j+t then
retJ=j
retT=t
exit for
endif
next
if retJ<>0 or retT<>0 then exit for
next
msgbox "鸡有" & retJ & "只 兔有" & retT & "只"