VB.net 3つの数字の平均2つの異なる方法。初心者の質問
質問
3つの入力値用の3つのテキストボックスと、出力用のリストボックスがあるフォームがあります。ユーザーが3つの異なる数字を入力し、ボタンをクリックして平均を見つけられるようにする必要があります。これをどうやってやるのか本当によくわかりません。どんな助けも大歓迎です。
まだ立ち往生しています...
Private Sub btnAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnAverage.Click
Dim a As Integer = CInt(txtone.Text)
Dim b As Integer = CInt(txtTwo.Text)
Dim c As Integer = CInt(txtThree.Text)
Dim average As Integer
average = (a + b + c) / 3
lstOutput.Text = average
解決
入力を数値に変換する方法が不明ですか?その場合は、CInt関数を使用します。
Public Sub OnAverageClick(ByVal sender as Object, ByVal e As EventArgs) Handles AverageButton.Click
Dim input1 as Integer = CInt(textBox1.Text)
Dim input2 as Integer = CInt(textBox2.Text)
Dim input3 as Integer = CInt(textBox3.Text)
Dim average = (input1 + input2 + input3) / 3
End Sub
他のヒント
@JaredPar
代わりにInteger.TryParseを使用します。
この関数は、任意の数の非ゼロ値の平均を計算します:
''' <summary>Calcula el Promedio de los Valores ingresados.
''' Sólo tiene en cuenta los Valores mayores que 0.</summary>
''' <param name="diasValores">Valores a Calcular</param>
Function PromedioValores(ByVal ParamArray diasValores() As Integer)
'Esta funcion calcula el promedio de los valores ingresados como parametro
Dim result As Double = 0
If diasValores.Length <= 0 Then Exit Function
Dim cant As Integer = 0
For i As Integer = 0 To UBound(diasValores, 1)
If diasValores(i) > 0 Then
cant = cant + 1
result += diasValores(i)
End If
Next i
If result > 0 Then
result = result / cant
End If
Return result
End Function
使用:
Me.TextBox1.Text = PromedioValores(10, 0, 0, 15, 0, 12, 12, 0)
protected sub on_btn_click()
listbox1.items.add(new listitem((integer.parse(textbox1.text) + integer.parse(textbox2.text) + integer.parse(textbox3.text)) / 3 ))
end sub
所属していません StackOverflow