vb中怎样实现计算1—n的奇偶数之和:(n为自然数)

2024-11-22 02:56:15
推荐回答(4个)
回答(1):

代码及注释如下:
Private sub command1_click()
for i=1 to n'i从1到n循环
if i mod 2=0 then'利用mod函数来判断i的值是偶数还是奇数
oushuhe=oushuhe+i'如果是偶数,就将其累加到oushuhe变量中
else
jishuhe=jishuhe+i'如果是奇数,就将其累加到技术和变量中
end if
next
msgbox "偶数和为" & oushuhe“,奇数和为"& jishuhe'利用msgbox显示结果
end sub

回答(2):

自己新建工程 添加你的控件 加入以下代码即可:

Option Explicit
Private Sub Form_Load()
Me.Caption = "计算"
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Label1.Caption = "请输入要就算的数"
Label2.Caption = "偶数和为:"
Label3.Caption = "奇数和为:"
End Sub

Private Sub Command1_Click()
Dim i
Dim a, b
For i = 1 To Val(Text1.Text)
If i Mod 2 = 0 Then
a = a + i
Else
b = b + i
End If
Next i
Text2.Text = a
Text3.Text = b
End Sub

回答(3):

Private Sub Command1_Click()
Dim a, b, i
For i = 1 To Val(Text1.Text)
If i\2 = 0 Then
a = a + i
Else
b = b + i
End If
Next i
Text2.Text = a
Text3.Text = b
End Sub

回答(4):

这么简单 自己改吧。
for i = 1 to 10 step 2 '奇数和
sum=sum+i
next i

for i = 2 to 10 step 2 '偶数和
sum=sum+i
next i

for i = 1 to 10
sum=sum+i
next i