VB.Net Tutorial/Operator/Operator — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 16:40, 26 мая 2010

Calculate PI

" Quote from
"Visual Basic 2005 Cookbook Solutions for VB 2005 Programmers
"by Tim Patrick (Author), John Craig (Author)
"# Publisher: O"Reilly Media, Inc. (September 21, 2006)
"# Language: English
"# ISBN-10: 0596101775
"# ISBN-13: 978-0596101770

Public Class Tester

    Public Shared Sub Main
      Console.WriteLine(FindPi(500))
    End Sub
    Private Shared NumberDigits As Integer
    Public Shared Function FindPi(ByVal digits As Integer) As String
        " ----- Calculate Pi to the specified number of digits,
        "       based on the formula:
        "          Pi/4 = arctan(1/2) + arctan(1/3)
        Dim result As New System.Text.StringBuilder("PI=3.")
        Dim digitIndex As Integer
        Dim divFactor As Integer
        " ----- Build an array that will hold manual calculations.
        NumberDigits = digits + 2
        Dim targetValue(NumberDigits) As Integer
        Dim sourceValue(NumberDigits) As Integer
        " ---- Perform the calculation.
        divFactor = 2
        ArcTangent(targetValue, sourceValue, divFactor)
        divFactor = 3
        ArcTangent(targetValue, sourceValue, divFactor)
        ArrayMult(targetValue, 4)
        " ----- Return a string version of the calculation.
        For digitIndex = 1 To NumberDigits - 3
            result.Append(Chr(targetValue(digitIndex) + Asc("0"c)))
        Next digitIndex
        Return result.ToString
    End Function
    Private Shared Sub ArrayMult(ByRef baseNumber() As Integer, _
            ByRef multiplier As Integer)
        " ----- Multiply an array number by another number by hand.
        "       The product remains in the array number.
        Dim carry As Integer
        Dim position As Integer
        Dim holdDigit As Integer
        " ----- Multiple each base digit, from right to left.
        For position = NumberDigits To 0 Step -1
            " ----- If the multiplication went past 9, carry the
            "       tens value to the next column.
            holdDigit = (baseNumber(position) * multiplier) + carry
            carry = holdDigit \ 10
            baseNumber(position) = holdDigit Mod 10
        Next position
    End Sub
    Private Shared Sub ArrayDivide(ByRef dividend() As Integer, ByRef divisor As Integer)
        " ----- Divide an array number by another number by hand.
        "       The quotient remains in the array number.
        Dim borrow As Integer
        Dim position As Integer
        Dim holdDigit As Integer
        " ----- Process division for each digit.
        For position = 0 To NumberDigits
            " ----- If the division can"t happen directly, borrow from
            "       the previous position.
            holdDigit = dividend(position) + borrow * 10
            dividend(position) = holdDigit \ divisor
            borrow = holdDigit Mod divisor
        Next position
    End Sub
    Private Shared Sub ArrayAdd(ByRef baseNumber() As Integer, ByRef addend() As Integer)
        " ----- Add two array numbers together.
        "       The sum remains in the first array number.
        Dim carry As Integer
        Dim position As Integer
        Dim holdDigit As Integer
        " ----- Add each digit from right to left.
        For position = NumberDigits To 0 Step -1
            " ----- If the sum goes beyond 9, carry the tens
            "       value to the next column.
            holdDigit = baseNumber(position) + addend(position) + carry
            carry = holdDigit \ 10
            baseNumber(position) = holdDigit Mod 10
        Next position
    End Sub
    Private Shared Sub ArraySub(ByRef minuend() As Integer, ByRef subtrahend() As Integer)
        " ----- Subtract one array number from another.
        "       The difference remains in the first array number.
        Dim borrow As Integer
        Dim position As Integer
        Dim holdDigit As Integer
        " ---- Subtract the digits from right to left.
        For position = NumberDigits To 0 Step -1
            " ----- If the subtraction would give a negative value
            "       for a column, we will have to borrow.
            holdDigit = minuend(position) - subtrahend(position) + 10
            borrow = holdDigit \ 10
            minuend(position) = holdDigit Mod 10
            If (borrow = 0) Then minuend(position - 1) -= 1
        Next position
    End Sub
    Private Shared Function ArrayZero(ByRef baseNumber() As Integer) As Boolean
        " ----- Report whether an array number is all zero.
        Dim position As Integer
        " ----- Examine each digit.
        For position = 0 To NumberDigits
            If (baseNumber(position) <> 0) Then
                " ----- The number is nonzero.
                Return False
            End If
        Next position
        " ----- The number is zero.
        Return True
    End Function
    Private Shared Sub ArcTangent(ByRef targetValue() As Integer, _
            ByRef sourceValue() As Integer, _
            ByVal divFactor As Integer)
        " ----- Calculate an arctangent of a fraction, 1/divFactor.
        "       This routine performs a modified Maclaurin series to 
        "       calculate the arctangent. The base formula is:
        "          arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9 - ...
        "       where -1 < x < 1 (it"s 1/divFactor in this case).
        Dim workingFactor As Integer
        Dim incremental As Integer
        " ----- Figure out the "x" part, 1/divFactor.
        sourceValue(0) = 1
        incremental = 1
        workingFactor = divFactor
        ArrayDivide(sourceValue, workingFactor)
        " ----- Add "x" to the total.
        ArrayAdd(targetValue, sourceValue)
        Do
            " ----- Perform the "- (xy)/y" part.
            ArrayMult(sourceValue, incremental)
            workingFactor = divFactor * divFactor
            ArrayDivide(sourceValue, workingFactor)
            incremental += 2
            workingFactor = incremental
            ArrayDivide(sourceValue, workingFactor)
            ArraySub(targetValue, sourceValue)
            " ----- Perform the "+ (xy)/y" part.
            ArrayMult(sourceValue, incremental)
            workingFactor = divFactor * divFactor
            ArrayDivide(sourceValue, workingFactor)
            incremental += 2
            workingFactor = incremental
            ArrayDivide(sourceValue, workingFactor)
            ArrayAdd(targetValue, sourceValue)
        Loop Until ArrayZero(sourceValue)
    End Sub
    
End Class
PI=3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211
7067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930
3819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491
4127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151
1609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011
9491

Compact operators

Public Class Tester

    Public Shared Sub Main
        Dim result As New System.Text.StringBuilder
        Dim testDouble As Double = Math.PI
        result.Append("Double ").AppendLine(testDouble)
        testDouble += Math.PI
        result.Append("+= ").AppendLine(testDouble)
        testDouble *= Math.PI
        result.Append("*= ").AppendLine(testDouble)
        testDouble -= Math.PI
        result.Append("-= ").AppendLine(testDouble)
        testDouble /= Math.PI
        result.Append("/= ").AppendLine(testDouble)
        testDouble ^= Math.PI
        result.Append("^= ").AppendLine(testDouble)
        result.AppendLine()
        Dim testInteger As Integer = 17
        result.Append("Integer ").AppendLine(testInteger)
        testInteger \= 2
        result.Append("\= 2 ... ").AppendLine(testInteger)
        testInteger += 1
        result.Append("+= 1 ... ").AppendLine(testInteger)
        testInteger <<= 1
        result.Append("<<= 1 ... ").AppendLine(testInteger)
        testInteger >>= 3
        result.Append(">>= 3 ... ").AppendLine(testInteger)
        result.AppendLine()
        Dim testString As String = "Abcdef"
        result.Append("String ").AppendLine(testString)
        testString &= "ghi"
        result.Append("&= ghi ... ").AppendLine(testString)
        testString += "jkl"
        result.Append("+= jkl ... ").AppendLine(testString)
        Console.WriteLine(result.ToString())
    End Sub
End Class
Double 3.14159265358979
+= 6.28318530717959
*= 19.7392088021787
-= 16.5976161485889
/= 5.28318530717959
^= 186.656996003562
Integer 17
\= 2 ... 8
+= 1 ... 9
<<= 1 ... 18
>>= 3 ... 2
String Abcdef
&= ghi ... Abcdefghi
+= jkl ... Abcdefghijkl

Prime numbers using the Sieve of Eratosthenes

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Collections
Public Class Tester
    Public Shared Sub Main
        Dim needBreak As Boolean = True
        Console.WriteLine("Prime numbers using the ""Sieve of Eratosthenes""")
        Dim index As Integer = 1
        Dim counter As Integer
        Do While (index < (MaxNumber - 1))
            index += 1
            If (PrimeStorage(index) = True) Then
                For counter = index * 2 To MaxNumber - 1 Step index
                    PrimeStorage(counter) = False
                Next counter
            End If
        Loop
        For counter = 2 To 7999999
            If (GetBit(counter) = 1) Then
                If (counter < 50) Or (counter > 7999800) Then
                    Console.WriteLine(counter)
                ElseIf (needBreak = True) Then
                    Console.WriteLine("...")
                    needBreak = False
                End If
            End If
        Next counter
    End Sub
    
    Private  Const MaxNumber As Integer = 8000000
    Private Shared PrimeStorage As New BitArray(MaxNumber, True)
    Public Shared Function GetBit(ByVal index As Integer) As Integer
        If (PrimeStorage(index) = True) Then Return 1 Else Return 0
    End Function
    
End Class
Prime numbers using the "Sieve of Eratosthenes
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
...
7999811
7999813
7999847
7999909
7999913
7999919
7999921
7999963
7999993

Using an assignment operator to calculate a power of 2

Module Tester
   Sub Main()
      Dim exponent As Integer " power input by user
      Dim result As Integer = 2 " number to raise to a power
      exponent = 12
      result ^= exponent " same as result = result ^ exponent
      Console.WriteLine("result = exponent: {0}", result)
      result = 2 " reset result to 2
      result = result ^ exponent
      Console.WriteLine("result = result  exponent: {0}", result)
   End Sub 
End Module
result ^= exponent: 4096
result = result ^ exponent: 4096