当前位置:编程学习 > VB >>

vb编程小问题

Private Sub Command1_Click()
a = Val(Text1.Text)
Print 2
For i = 3 To a
For x = 2 To (i - 1)
If i Mod x = 0 Then Exit For Else t = t + 1
If t = i - 2 Then Print i
Next x
Next i
End Sub
究竟哪错了,运行时如果输入大于10的数也只会打2 3 5 7

拜求答案

补充:这是一个求N以内的质数的程序,但我输入100,得到的却仍然是 2  3  5  7

追问:谢谢你,但是 if x=i then print i,我没太看懂

还有,有时窗体打出的数太多,我想加一个滚动条该怎么加?

如能解答,追加20分

答案:Private Sub Command1_Click()
a = Val(Text1.Text)
Print 2
For i = 3 To a
For x = 2 To (i - 1)
If i Mod x = 0 Then Exit For
Next x

 

If x = i Then Print i
Next i
End Sub

调用API的功能实现,
因相应的API较复杂,不太好理解,我用子程序对它做了封装。
实际使用过程中你将下面这段代码Copy到程序模块中,然后调用SubOpenFile子程序就行了。
'注意在引用该FSO功能时先引用 Microsoft Scripting Runtime
Public ObjFso As New FileSystemObject
Declare Function shellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Public Sub SubOpenFile(ByVal FileSaveName As String, ByVal StrFrmName As Form)
'打开文件
'输入:sFileName 待打开文件的全路径加上文件名,如 "F:\VB\RunExe\Module1.bas"
'输入:调用该子程序的窗体名称
If Not ObjFso.FileExists(FileSaveName) Then
MsgBox ("没有找到要打开的文件")
Exit Sub
End If
sCorrectPath = ObjFso.GetParentFolderName(FileSaveName)
sFileName = ObjFso.GetFileName(FileSaveName)
'输入:调用该子程序的窗体名称
lHwnd = StrFrmName.hwnd
'lShellFile = shellExecute(lHwnd, "open", FileSaveName, vbNullString, sCorrectPath, SW_SHOWNORMAL)
lShellFile = shellExecute(lHwnd, "open", FileSaveName, vbNullString, sCorrectPath, 5)
'错误处理
If lShellFile > 32 Then
Exit Sub
Else
Select Case lShellFile
Case 2
If Right(sFileName, 3) <> "htm" Then
MsgBox "File Not Found.", vbCritical + vbOKOnly, "X-File:"
End If
Exit Sub
Case 3
MsgBox "Path not Found.", vbCritical + vbOKOnly, "X-File:"
Exit Sub
Case 5
MsgBox "Access denied.", vbCritical + vbOKOnly, "X-File:"
Exit Sub
Case 8
MsgBox "Out of Memory.", vbCritical + vbOKOnly, "X-File:"
Exit Sub
Case 32
MsgBox "Shell32.dll not Found.", vbCritical + vbOKOnly, "X-File:"
Exit Sub
End Select
End If
在一个for 下面加一句 : t=0
变量t没有用,两行If 语句这么改就行了(我把If语句改为语句块):
If i Mod x = 0 Then
    Exit For      '这两行和你 写的其实一样,即遇到合数则退出For循环
Else      '不是合数(即质数)
    Print i
    Exit For       '将质数打印后退出循环,以免将同一质数重复打印
End If

另外给出一个建议:将x=2 To (i-1)改为x=2 To Int(i/2) ,这样可以简化算法时间复杂度

上一个:怎样学好VB编程?
下一个:vb编程数组问题

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,