I asked a question earlier about comparing numbers using the "And" comparison operator in If Statements and now I have been toying around with getting my head wrapped around bitwise operators. So I have written a very basic code that will allow me to see the conversion of any decimal number in binary format.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(ConvertToBinary(-1))
End Sub
Public Function ConvertToBinary(ByVal someInteger As SByte) As String
Dim converted As String = Convert.ToString(someInteger, 2) '.PadLeft(8, "a"c)
Return converted
End Function
Notice here that I am using SByte as the paramerter - which should only contain 8 bits right? However, the message box that appears has 16 bits assigned to negative numbers. Positive numbers have the correct 8.
There is no Convert.ToString overload that takes an SByte, so the SByte is being implicitly converted to a Short.
Related
How to make Visual Basic .NET recognize two or more digits instead of one?
When I execute it, it only validates correctly in case both numbers are one digit.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim menorOigual As Boolean
menorOigual = numero1.Text <= numero2.Text
MsgBox(menorOigual)
End Sub
By comparing the value of the Text properties, you're comparing strings, which is why it only works with single digits (because as a string "10" comes before "3", because each character is compared in turn). You need to convert the strings to a numeric type like integer, e.g.
Convert.ToInt32(numero1.Text)
For production code, you'll probably also need to validate the conversion, so see also:
Integer.TryParse
Can anyone pls send me a link where the method of converting from Hexadecimal to Decimal is explained? I am not understanding why the "Short" type variable is showing a negative sign in the below example...the literal seems to be the same in both cases. I understand UShort will not take signed values but then where is the negative sign even coming from ...the literals are exactly same in both cases. Is it because I am not understanding the rules of conversion from Hexadecimal to Decimal or is it something else?
Module Module1
Sub Main()
Dim counter As Short = &H8000S 'Output: -32768
Dim flags As UShort = &H8000US 'Output: 32768
Console.WriteLine("O/P: {0} {1}", counter, flags)
Console.ReadLine()
End Sub
End Module
Requesting your help to understand the concept of widening better!
I came across the following statement w.r.t 'Widening Conversion' in VB.Net. From the msdn documentation on the topic I found the following: Widening conversions preserve the source value but can change its representation. This occurs if you convert from an integral type to Decimal, or from Char to String. The link to the page is found below:
https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/widening-and-narrowing-conversions
My Question is as follows: I wrote the following code to understand the meaning of the statement "...preserve the source value but can change its representation". But I see no difference in the output when I print the integer or the decimal. Then what does the phrase mean....what is the meaning of "...can change its representation"?
Module Module1
Sub Main()
Dim i As Integer = 5
Dim d As Decimal = i 'widening
Console.WriteLine(i)
Console.WriteLine(d)
'Both prints "5"...no difference in representation
Console.ReadLine()
End Sub
End Module
Can someone also please give an example to demonstrate how the representation changes when we convert a char value to a string?
It means the internal presentation of the number (in your case). Try to convert, say, Single to Double:
Sub Main(args As String())
Dim sng As Single = 1.23E+32
Dim dbl As Double = sng
Console.WriteLine($"Single: {sng}")
Console.WriteLine($"Double: {dbl}")
End Sub
' Output:
' Single: 1,23E+32
' Double: 1,2300000079302825E+32
I am using the Graph Control made by a user named "Aeonhack" in my .NET application. When adding, let's say, a point with the size 9, it has to be a Single like 9.0F.
So I want a function that converts an Integer like 9 into a single like 9.0F.
The normal CType won't work, and I also tried:
Private Function IntToSingle(ByVal Number As Integer) As Single
Return CType(Number & ".0F", Single)
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GraphConnections.AddValue(IntToSingle(7))
End Sub
This gives me this error:
Conversion from string "7.0F" to type 'Single' is not valid.
How can I fix this?
Use Convert.ToSingle:
Convert.ToSingle(Number)
Or just CType, without weird string concatenation:
CType(Number, Single)
I think the confusion is with 7.0F. That is not the same thing as the string "7.0F".
Per Microsoft
Appending the literal type character F to a literal forces it to the
single data type.
You could simply use the F to force a double literal to be a single data type.
GraphConnections.AddValue(7.0F)
If, however, you receive an integer variable, then you would need to convert or cast it to a single as suggested by #MarcinJuraszek.
dim point As Integer = 7
GraphConnections.AddValue(Convert.ToSingle(point))
You can use this to convert to a single: CSng(9), though I think this only works in VB.NET.
This is what i have so far. cant seem to get it to work these are the guidelines
***Specifics
You will use 1 file to enter all the scores. The file is named Data.txt and should be stored in the projects Debug folder. The scores are floating point numbers.
One button should calculate the mean, range, and standard deviation and display them.
You must use separate functions to calculate the 3 statistics.
One button should display the frequencies in tabular form. For this exercise, the frequencies we are interested in are as follows:
# scores < 60
60 <= # scores < 70
70 <= # scores < 80
80 <= # scores < 90
90 <= # scores
You must use a separate array to hold the totals for the individual ranges.
All scores should be displayed in a listbox.*
Option Strict On
Public Class Form1
Private names() As String = IO.File.ReadAllLines("data.txt")
Private scores(names.Count - 1) As double
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To names.Count - 1
scores(i) = CInt(names(i))
Next
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sum As Double = 0
mean(sum)
OutputListBox.Items.Add(sum)
End Sub
Function mean(ByRef sum As Double) As Double
Dim total As Double = scores(0)
For i As Double = 0 To scores.Count - 1
sum =
Next
Return sum
End Function
End Class
I won't do all of the work for you, but here is a restructuring of your form with the mean implemented and some comments so you can figure out what is happening:
Option Strict On
Option Explicit On
Partial Public Class Form1
Private scores() As Double
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' Clear the list view
ListView1.Clear()
' First, load the scores from the file into memory
Call LoadScores()
Dim value As Double
' Next, calculate the mean
value = CalculateMean()
' And add it to the list view
ListView1.Items.Add("Mean = " & value.ToString)
' Now calculate the other items and display them
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
''' <summary>
''' This method loads the scores from the file into the scores array
''' </summary>
''' <remarks></remarks>
Private Sub LoadScores()
Dim stringScores() As String
' Read all of the scores in the file into an array of strings
stringScores = IO.File.ReadAllLines("data.txt")
' Resize the scores array to hold all of the values in the file
ReDim scores(stringScores.Length)
Dim counter As Integer
' Now convert those strings to numbers, and store them in scores
For Each sValue As String In stringScores
' Convert the string value from the file into a double and store it in the current location in the scores array
scores(counter) = CDbl(sValue)
' Keep track of our position in the scores array
counter += 1
Next
End Sub
''' <summary>
''' The mean is the sum of the scores divided by the total number of scores
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Function CalculateMean() As Double
If scores.Length <> 0 Then
Dim total As Double
For Each value As Double In scores
total += value
Next
Return total / scores.Length
Else
' Avoid a divide by zero error
Return 0
End If
End Function
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
End Class
As with any problem, start by breaking it down and do one piece at a time. A common approach is to make one function implement one (or one part of a) requirement, so start there.
Read the file to get the scores. For this exercise, you have a hard-coded name, but it is just as easy to make the file reading function take the name as a parameter. You know the scores are listed as floating-point numbers, so you will return them as Double or Single. I see that you used an array in the code you have so far, so we'll stick with that. With that information, we can make the signature of the function
Public Function ReadScoresFromFile(fileName As String) As Double()
Calculate the mean, range, and standard deviation; three things, three functions. Based on the mathematical definitions of these three things, you will need functions that take in a sequence of numbers and will return one number. This should lead you to the function definitions:
Public Function Mean(values As Double()) As Double
Public Function Range(values As Double()) As Double
Public Function StandardDeviation(values As Double()) As Double
A quick search online or through your math/statistics book should give you definitions and formulas that you can turn into code. Hint: You may be able to call one function from one of the others to simplify the work.
Group scores into ranges. As with the file name, you have a specified list of ranges. You could try to parametrize the function to take the ranges as an argument, but its probably not worth the effort for this exercise. So, we know have a sequence of scores and need a list of total of number of scores in each range. Since totals will be integral numbers and not floating-point, we'll pick the type accordingly.
Public Function CountInRanges(scores as Double()) As Integer()
At this point, you have all the functions you need to get the data you need. Now you just have to make the various button click handlers call the appropriate functions and put the results in the appropriate labels, list boxes, etc. Use the arguments and return types to help you figure out the flow of data from one function to the next, using variables as needed to hold intermediate results.
A few things I noticed from the code you showed (none of these are required to solve your immediate problem, but could be helpful now and in the future.):
Try to give your controls meaningful names. AggregatesButton, RangesButton, MeanLabel, etc are much easier to remember than Button1, Button2, etc. (There are various styles for names as well. Some people will use a prefix instead of a suffix for names like btnAggregates, btnRanges, lblMean.)
The numeric types all have a Shared Parse method. You may consider using this instead of the conversion as it allows you to specify several options about how to parse the number from a string. For now, the conversion will probably suffice, but this is at least something to tuck away for later.
I don't know what topics your class will cover later, but you may consider looking into the For Each loop instead of the standard For loop. This can be useful when you need to do something 'for each' item in a sequence but don't care about the index, such as the Mean, Range, StandardDeviation, and CountInRanges calculations. This can make your code cleaner because you won't keep referencing the array and makes it easier to convert to other sequence classes that you may run into later (eg: List, Collection, etc). It also keeps you from accidentally modifying the array, which you never want to do in any of those functions.