My task in VB.NET is as follows: Sum a number until it becomes a whole number and count how many times it was summed
Sorry, I know that is not that hard but I am new to coding
example: I have this number 4.25
sum until he gets a whole number: 4.25 4.25 4.25 4.25 = 17 and count how many times he was sumed: 4 times
How to do that in VB.NET ?
CodePudding user response:
You can create a counter, increment it each time you add sum
to sum
:
Dim cnt As Integer = 1
While sum <> Int(sum)
cnt = cnt 1
sum = sum original
End While
CodePudding user response:
Someone in your class might tackle it this way...
If you look at the number as a fraction—from your example 4¼—you can see that you would have to multiply by the denominator (4) to get a whole number.
So, all you need to do is convert the fractional part to the simplest fraction and use the denominator.
Module Module1
Dim decSep As String = Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator
Public Function GCD(a As Long, b As Long) As Long
' Copied from https://www.programmingalgorithms.com/algorithm/greatest-common-divisor/vb-net/
'TODO: Consider using a more efficient algorithm.
If a = 0 Then
Return b
End If
While b <> 0
If a > b Then
a -= b
Else
b -= a
End If
End While
Return a
End Function
Sub Main()
Console.Write("Enter a number: ")
Dim inp = Console.ReadLine()
'TODO: Check that the input has a decimal separator with digits after it.
Dim fracPart = inp.Substring(inp.IndexOf(decSep) 1)
Dim numerator = Convert.ToInt64(fracPart)
Dim denominator = CLng(Math.Pow(10, fracPart.Length))
Dim a = GCD(numerator, denominator)
Dim mult = denominator / a
Dim orig = Decimal.Parse(inp)
Console.WriteLine($"You need to add {inp} to itself {mult} times to get the whole number {mult * orig}.")
Console.ReadLine()
End Sub
End Module
Sample run:
Enter a number: 1.6125
You need to add 1.6125 to itself 80 times to get the whole number 129.