我在 VB.NET 中的任務如下:將一個數字求和直到它變成一個整數并計算它被求和的次數
抱歉,我知道這并不難,但我是編碼新手
例子:我有這個數字 4.25
求和直到他得到一個整數:4.25 4.25 4.25 4.25 = 17 并計算他被求和的次數:4 次
如何在 VB.NET 中做到這一點?
uj5u.com熱心網友回復:
您可以創建一個計數器,每次添加時遞增sum
它sum
:
Dim cnt As Integer = 1
While sum <> Int(sum)
cnt = cnt 1
sum = sum original
End While
uj5u.com熱心網友回復:
你班上的某個人可能會這樣處理它......
如果您將數字視為分數(例如 4?),您會發現必須乘以分母 (4) 才能得到整數。
因此,您需要做的就是將小數部分轉換為最簡單的分數并使用分母。
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
樣本運行:
Enter a number: 1.6125
You need to add 1.6125 to itself 80 times to get the whole number 129.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/536768.html
標籤:网络
上一篇:VMware安裝kali作業系統