VB.NET Divisions problems - vb.net

First of all, I would like you to know that I am really rookie on this platform and in vb.net language. I have a question, I wanted to ask you, since I couldn't make any progress in about 3 hours. I think it's very simple for someone who knows.
If the number entered from the textbox is odd, multiply by 3 and add 1, if it is double, this process will be divided by 2, and this process should continue until the number is "1". I try to write the code of the program that finds how many steps this process takes (number of processes), the maximum value of the number during the process and the number that the number always reaches 1 in pairs with VB.NET.
Is there anyone who can help? I want you to know that I was really struggling, trying to learn, but not enough
As I said, I scribbled something, but I am not even on the right track.
enter image description here
enter code here
Dim number1 As Double
Dim tislem As Double
Dim result As Double
Dim çislem As Double
Dim i As Double
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
number1 = TextBox1.Text
çislem = number1 / 2
tislem = number1 * 3 + 1
If number1 Mod (2) = 1 Then
result = tislem
MessageBox.Show("sayı tektir" + result.ToString())
For i = 1 To result = 0
result = number1 / 2
Next i
MessageBox.Show("sayı tektir" + result.ToString())
Else MessageBox.Show("sayı çifttir")
End If
End Sub

I'm not sure if I understood exactly what you're trying to do (neither of us have english as a first language it seems). I'm still trying, but make sure that you understand what I'm doing or I may lead you off target.
It seems to me that the worst problem here is using a For loop instead of a While loop. You could also do without some of these variables. Here's some code to give you a hand:
' I suggest that you add these two lines at the very top of your code
' It'll force you to type your variables, which is a great way to avoid all kind of mistakes
Option Explicit On
Option Strict On
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Here I'm protecting you against errors caused if the user enters a non-numeric
' Your teached probably didn't ask for this but it's good to know nonetheless
If Not String.IsNullOrWhiteSpace(TextBox1.Text) AndAlso IsNumeric(TextBox1.Text) Then
' Converting text to double (it was done implicitely in your code, but it's better to understand what's happening to better control it)
Dim myNumber As Double = CDbl(TextBox1.Text) ' CDbl as in 'Convert DouBLe'
Dim maxNumber as Double = myNumber
' If the number is odd, we multiply by 3 and add 1
If myNumber Mod 2 = 1 Then
myNumber = (myNumber * 3) + 1
If myNumber > maxNumber Then maxNumber = myNumber
End If
' Let's count how many divisions before there's only 1 left
Dim i As Integer = 0
While (myNumber > 1)
myNumber = myNumber / 2
i += 1
End While
MessageBox.Show("It took " & i.ToString & " divisions until my number was reduced to 1. The max number was " & maxNumber.ToString & ".")
Else
' This will appear if you try to use non-numeric, like letters
MessageBox.Show("Use only numbers.")
End If
End Sub
Have fun!

Try something like this,
Dim number1 As Double
Dim maxNumber As Double = 0
Dim steps as Double = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
number1 = TextBox1.Text
MessageBox.Show($"Sayı {If( (number1 Mod 2) = 1, "tektir", "çifttir") }")
While number1 > 1
number1 = If((number1 Mod 2) = 1, number1 * 3 + 1, number1 * 2)
maxNumber = Math.Max(number1, maxNumber)
steps += 1
End While
MessageBox.Show($"Steps: {steps}{Environment.NewLine}Max number reached: {maxNumber}")
End Sub
You should write a proper loop in order to repeat this process until you reach 1. Moreover, it is better for you that if you get used to use & symbol instead of + symbol to concat strings.

Related

Same number is generated in RNG in VB.NET

I am attempting to make a random number generator in VB 16 in Visual Studio, but every time I run this I keep getting 71, I've tried making it public, sharing it and several other things, but it won't work. I am trying to make a program that has the user guess a randomly generated number, and continue guessing until they get it, but for some reason the exact same number is chosen each time. It won't work properly specifically in window app forms. How do I get a random number each time?
Public Shared Randomize()
Dim value As Integer = CInt(Int((100 * Rnd()) + 1))
Public Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Dim entervalue As String = EnterTxt.Text
Dim chances As Integer
Select Case entervalue
Case > value
ResTxt.Text = "Too big"
chances += 1
Case < value
ResTxt.Text = "Too small"
chances += 1
Case = value
ResTxt.Text = "Well done, you got it in " & chances & " tries"
End Select
End Sub
You were close! Here's a working example modifying your original logic:
Private random As Random = New Random()
Private value As Integer
Private chances As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
value = random.Next(1, 100)
chances = 0
End Sub
Private Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Select Case EnterTxt.Text
Case > value
chances += 1
ResTxt.Text = "Too big"
Case < value
chances += 1
ResTxt.Text = "Too small"
Case = value
chances += 1
ResTxt.Text = "Well done, you got it in " & chances & " tries"
'and reset for next attempt
value = random.Next(1, 100)
chances = 0
End Select
End Sub
Since your code is not correct it is hard to pinpoint the problem. It is also not clear what the code is supposed to do.
Try this
Private Shared PRNG As New Random ' add this
value = PRNG.Next(1, 101)'this will set value to a random number between 1 and 100 inclusive
Here's some skeleton code for you:
Dim rnd As New Random()
For i as Integer = 0 to 10
Console.WriteLine("{0,15:N0}", rnd.Next())
Next
Notice the rnd.Next() thing. Hope it helps.

Visual basic For Next not repeating and not incrementing by 1

I am currently working on a homework assignment for Visual basic. The homework is to display the square value of only the odd numbers 1-9. I have to use a For Next to do so as specified by the assignment. I do not want the answer but a point to the right direction. Here is my code currently it only displays the square value of 9 but will not display the square value of the other odd numbers. I have done a couple tutorials but I can not figure out why it ill not continue the loop.
Public Class MainForm
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub displayButton_Click(sender As Object, e As EventArgs) Handles displayButton.Click
'Start/end values and retainer for the values
Dim startVal As Integer
Dim endVal As Integer
Dim squareVal As Integer
startVal = 1
endVal = 9
'For loop to separate the odd and even numbers to square the odd numbers.
For _val As Integer = startVal To endVal Step 1
If _val Mod 2 <> 0 Then
squareVal = _val * _val
squaresLabel.Text = squareVal.ToString() & ControlChars.NewLine
_val += 1
Else
squaresLabel.Text = _val.ToString() & ControlChars.NewLine
_val += 1
End If
Next _val
End Sub
End Class
You are overwriting the text stored in squaresLabel each pass through the loop. Look at the assignment statement:
squaresLabel.Text = squareVal.ToString() & ControlChars.NewLine
I think you are just repeating the calculation not actually output each value. So I suggest you define an array and store them inside of it. Also do trouble shooting for each value. Hope it helps.

Detect the sign in number input

how can i detect if the input number in textbox contains "-"
so i can change the output into positive number and
if not contain "-" the output number is become negative
i'm using Vb.net 2010 tnx in advance for who wants to help
Dim output As String
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If getbyte(TextBox1.Text, 0) = Chr(45) Then ' check whether the first character is - or not
output = New String((From c As Char In TextBox1.Text Select c Where Char.IsDigit(c)).ToArray())
else
output="-" & textbox1.text
End If
msgbox (CInt(output))' will give the number
End Sub
Getbyte function to take each character from a string based on the position
Private Function getbyte(ByVal s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function
if you want to convert the -eve number to positive for calculation you can use
You have couple of options, two of them are:
1) Use StartsWith functions:
If Textbox1.Text.Trim().StartsWith("-"))Then
' It is a negative number
End If
2) If you just need to toggle the number sign, then:
Dim number as Integer = Integer.Parse(Textbox1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Using option2, i get:
Dim txta1 As New TextBox
txta1.Text = "-2"
Dim number As Double = Double.Parse(txta1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Dim s As String = number & " | "
Output: 2 |

Getting even/odd numbers specifically with a random number generator in visual basic [duplicate]

This question already has answers here:
Generating Even Random Numbers
(2 answers)
Closed 8 years ago.
trying to make a random number generator using visual basic for a school project. The user would enter in 2 different values in textbox1 and textbox 2, press a button and a random number would be generated between these 2 digits (this random number would be displayed in textbox3). This was too basic for the project, so i decided to add in 2 checkboxs which, when checked would make the generated number either even or odd.
Really need some help with an algorithm that limits the random number to be even or odd. Any help is greatly appreciated! :) (checkbox1 is for making it even, checkbox2 for odd)
Dim answer As Integer
Dim result As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox3.Clear()
TextBox3.Text = answer
If CheckBox1.Checked = False And CheckBox2.Checked = False Then
answer = CInt(Int((TextBox2.Text * Rnd() + TextBox1.Text)))
End If
^ the above code also seems to generate random numbers in a specific order, always starting from 0, any help with this would be greatly appreciated :)
If CheckBox1.Checked = True Then
Do Until result = 0
result = CDec(TextBox1.Text / 2) - CInt(TextBox1.Text / 2)
Loop
If result = 0 Then
answer = CInt(Int((TextBox2.Text * Rnd() + TextBox1.Text)))
End If
End If
End Sub
This is what I'd do to solve this problem:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles Button1.Click
'Parse the two numbers
Dim minValue = Integer.Parse(TextBox1.Text)
Dim maxValue = Integer.Parse(TextBox2.Text)
'Create a list of all possible valid numbers
Dim values = Enumerable.Range(minValue, maxValue - minValue).ToArray()
'Keep only the even numbers if selected
If CheckBox1.Checked Then
values = values.Where(Function (v) v Mod 2 = 0).ToArray()
End If
'Keep only the odd numbers if selected
If CheckBox2.Checked Then
values = values.Where(Function (v) v Mod 2 = 1).ToArray()
End If
'Check there are numbers
If values.Length = 0 Then
TextBox3.Text = "There no available numbers to choose."
Else
'`rnd` here is `System.Random` as I didn't know what `Rnd()` was.
TextBox3.Text = values(rnd.Next(0, values.Length)).ToString()
End If
End Sub
You could use a function to generate either an even or odd number depending on which checkbox is checked, the functions would use mod to determine whether the generated number id even/odd. If it is not what you require, then it would try again until the generated number matches. For example:
Private Sub btnGenerate_Click(sender As System.Object, e As System.EventArgs) Handles btnGenerate.Click
If chkOdd.Checked Then
GenerateOdd()
ElseIf chkEven.Checked Then
GenerateEven()
End If
End Sub
Private Function GenerateOdd()
Dim r = CInt(Math.Ceiling(Rnd() * 100))
If ((r Mod 2) = 0) Then
'r is even, generate another number and try again
GenerateOdd()
Else
'r is odd we have a match
yourTextBox.Text = r
Return r
End If
Return Nothing
End Function
Private Function GenerateEven()
Dim r = CInt(Math.Ceiling(Rnd() * 100))
If ((r Mod 2) = 0) Then
'r is even, we have a match
yourTextBox.Text = r
Return r
Else
'r is odd, generate another number and try again
GenerateEven()
End If
Return Nothing
End Function
I haven't tried this but you get the point!
*Edit - the (Rnd() * 100)) is a random number between 1 and 100

Visual Basic - Looping an array 100 times not working?

I'm trying to loop this array 100 times (gets a number from 0-99,999). I've tried it several different ways with no luck. I've got it set up so you click a button and it generates the array. The user will then enter a number and hit the other button to check how many times that number shows up in the group of a 100 numbers. Any thoughts how to fix it? I'm stuck.
Dim i As Integer
Dim rnd As New Random()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click
Dim num As Integer
If Int32.TryParse(txtEnter.Text, num) AndAlso num >= 0 AndAlso num < 10 Then
lblNumber.Text = i.ToString()
Dim counts = From c In i.ToString()
Group By c Into Group
Select DigitGroup = New With {.Count = Group.Count(), .Digit = c, .Group = Group}
Order By DigitGroup.Count Descending, DigitGroup.Digit
Dim numCount = counts.FirstOrDefault(Function(grp) grp.Digit.ToString() = num.ToString())
If numCount IsNot Nothing Then
Dim numMessage = String.Format("There are {0} number {1}'s found.", numCount.Count, num)
MessageBox.Show(numMessage)
Else
MessageBox.Show("Your number does not contain a " & num)
End If
Else
MessageBox.Show("Please enter a number between 0 and 9.")
End If
End Sub
Private Sub btnGetNumber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetNumber.Click
btnEnter.Enabled = True
i = 0
Do Until i > 100
Dim randomInt = rnd.Next(0, 100000)
i = i + 1
i = rnd.Next(0, 100000)
Loop
End Sub
End Class
First of all, it is common to use For Loops when you know the number of loops.
Secondly, you forgot to increment i in the until loop
Finally, you don't need to redeclare rnd in every loop. Something like that sounds better to me :
Dim rnd As New Random()
For i = 1 To 100
Dim randomInt = rnd.Next( 0 , 100000 )
Next
Move the New Random() out of that loop. Make it global and create the instance just one time.
(The Random generator starts using a seed obtained from the current time. Declaring a Random variable inside a loop result in the same seed used again and again. This gives back the same number defeating the randomness of the function) It is like: http://xkcd.com/221/
See another explanation here
Of course, if you don't increment the variable i used to control the loop, you will loop forever
Dim i As Integer
Dim rnd As New Random()
.....
i = 0
Do Until i > 100
Dim randomInt = rnd.Next(0, 100000)
i = i + 1
Loop
Said that, now I can't get what are you trying to do here. There is no array to check and you do not use the value obtained from the Random generator, simply, your i variable exits with value 101.
Now I am just guessing what are your intentions, but perhaps you want just this?
i = rnd.Next(0, 100000)
This will give to the variable i a random number and your subsequent code checks how many, of the required digit, are present in i
I see that you are not adding the variable "i" to increment:
i = 1
Do Until i > 100
Dim rnd As New Random()
Dim randomInt = rnd.Next(0, 100000)
i+=1 'Increment value of i by 1, same as i = i + 1
Loop
The variable of "i" will always be 1 if not incremented. Check that and let me know if that solves the problem!