查找字符串中所有数字的平均值 [英] Find average of all digits in string
问题描述
我想要查找数字的计数,最小的数字,最高的数字,以及字符串中所有数字的平均值。
公共类Form1
Private Sub Button1_Click(sender As Object, e As EventArgs)句柄Button1.Click
Dim i As Integer = 0
Dim minimumInt As Integer
Dim maximumInt As Integer
Dim averageInt As Single
对于每个c As (c)然后
如果(Asc(c) minimumInt = Asc(c)
ElseIf(Asc(c)> maximumInt)then
maximumInt = Asc(c)
End If
averageInt = averageInt + Asc(c)
averageInt = averageInt / i
End If
Next
MessageBox.Show(Total Digits:& i& ControlChars.CrLf& 平均数:&平均值ControlChars.CrLf& 最低数量:& minimumInt& ControlChars.CrLf& 最大数目:& maximumInt)
End Sub
结束类
我相信问题涉及转换例如,当TextBox1包含X13210AS时,我得到
I'm trying to find the count of the digits, the lowest digit, the highest digit, and the average of all the digits in a string.
This is what I was able to come up with so far
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer = 0
Dim minimumInt As Integer
Dim maximumInt As Integer
Dim averageInt As Single
For Each c As Char In TextBox1.Text
If Char.IsDigit(c) Then
i = i + 1
If (Asc(c) < minimumInt) Then
minimumInt = Asc(c)
ElseIf (Asc(c) > maximumInt) Then
maximumInt = Asc(c)
End If
averageInt = averageInt + Asc(c)
averageInt = averageInt / i
End If
Next
MessageBox.Show("Total Digits: " & i & ControlChars.CrLf & "Average Number: " & averageInt & ControlChars.CrLf & "Minimum Number: " & minimumInt & ControlChars.CrLf & "Maximum Number: " & maximumInt)
End Sub
End Class
I believe the issue is involving converting Chars to Integers.
For example, when TextBox1 contains "X13210AS", I get this http://i.imgur.com/5aaOWC0.png
When I should be getting an average of 1.4 and highest digit 3.
Any ideas on how to fix this while still using the majority of my code?
The first issue is with the ASCII conversion. "0" char is having value of 48.
The second issue is with your averaging, which should be done after you get all numbers instead of each loop. And beware of division by 0!
To get it right, you have to do this:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer = 0
Dim minimumInt As Integer
Dim maximumInt As Integer
Dim averageInt As Single
Dim intVal As Integer 'only use this
For Each c As Char In TextBox1.Text
If Char.IsDigit(c) Then
i = i + 1
intVal = Asc(c) - 48 'count this once, note -48 here is to convert ASCII rep to integer value
If (intVal < minimumInt) Then
minimumInt = intVal
ElseIf (intVal > maximumInt) Then
maximumInt = intVal
End If
averageInt += intVal
End If
Next
If i <> 0 Then 'beware of 0
averageInt = averageInt / i `put this outside
End If
MessageBox.Show("Total Digits: " & i & ControlChars.CrLf & "Average Number: " & averageInt & ControlChars.CrLf & "Minimum Number: " & minimumInt & ControlChars.CrLf & "Maximum Number: " & maximumInt)
End Sub
End Class
And you will get this:
这篇关于查找字符串中所有数字的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!