2012年3月14日 星期三

簡易大數減法

輸入兩數N1、N2,做大數的減法。 (N1、N2皆無限制)

輸入:
1000000000000000000000000
1

輸出:
999999999999999999999999

4 則留言:

  1. Dim a, b, e As Integer
    Dim x, y
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Line Input #1, x
    Line Input #1, y
    a = Len(x)
    b = Len(y)
    Do
    If a > b Then
    y = 0 & y
    Else
    x = 0 & x
    End If
    a = Len(x)
    b = Len(y)
    Loop Until a = b
    If x < y Then
    Call t(a)
    Else
    For i = a To 1 Step -1
    c = Val(Mid(x, i, 1))
    d = Val(Mid(y, i, 1))
    If f <> 0 Then c = c - f
    f = 0
    If c < 0 Then c = c + 10: f = f + 1
    e = c - d
    If e < 0 Then
    f = f + 1
    e = e + 10
    End If
    If i = 1 And e = 0 Then Exit For
    ans = e & ans
    Next
    Print #2, ans
    End If
    Close
    Close
    End
    End Sub
    Function t(a)
    For i = a To 1 Step -1
    d = Val(Mid(x, i, 1))
    c = Val(Mid(y, i, 1))
    If f <> 0 Then c = c - f
    f = 0
    If c < 0 Then c = c + 10: f = f + 1
    e = c - d
    If e < 0 Then
    f = f + 1
    e = e + 10
    End If
    If i = 1 And e = 0 Then Exit For
    ans = e & ans
    Next
    Print #2, "-" & ans
    End Function

    回覆刪除
  2. 小冰好,
    練習用函數是好的。
    但是,這題應該是將減法的分部,寫成函數。
    先判斷x,y誰大,然後丟進函數去的都是f(b,s),然後將結果加上該有的正負號。
    程式正確。

    回覆刪除
  3. 作者已經移除這則留言。

    回覆刪除
  4. Private Sub Form_Load()
    Dim arr(), brr() As Integer
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Line Input #1, n1
    Line Input #1, n2
    a = Len(n1)
    b = Len(n2)
    Do
    If a > b Then
    n2 = "0" & n2
    Else
    n1 = "0" & n1
    End If
    a = Len(n1)
    b = Len(n2)
    Loop Until a = b
    ReDim arr(a), brr(a)
    For i = 1 To a
    arr(i) = Val(Mid(n1, i, 1))
    brr(i) = Val(Mid(n2, i, 1))
    Next i
    If arr(1) > brr(1) Then
    For i = a To 1 Step -1
    q = arr(i) - brr(i)
    If q < 0 Then
    q = q + 10
    arr(i - 1) = arr(i - 1) - 1
    ans = q & ans
    Else
    ans = q & ans
    End If
    Next i
    Else
    For i = a To 1 Step -1
    q = brr(i) - arr(i)
    If q < 0 Then
    q = q + 10
    brr(i - 1) = brr(i - 1) - 1
    ans = q & ans
    Else
    ans = q & ans
    End If
    Next i
    End If
    ans = Replace(ans, "0", "")
    Print #2, ans
    Close #2
    Close #1
    end
    End Sub

    回覆刪除