加法的運算是把2 個整數靠右對齊,然後由右至左,一位一位相加。如果相加的結果大於等於10 就有進位(carry)發生。請寫個程式來判斷兩個正整數相加時,產生了幾次進位的情況。
輸入說明:
第一行的數字,表示有幾組測試資料,第二行開始的每一行即為一筆測試資料。每一行
輸入的資料有兩個正整數,以一個空格分開,每個整數的長度均小於100 位數。
輸出說明:
對每一筆測試資料,輸出相加後有幾次進位的次數。
輸入範例:
2
123 456
555 555
第一行的數字,表示有幾組測試資料,第二行開始的每一行即為一筆測試資料。每一行
輸入的資料有兩個正整數,以一個空格分開,每個整數的長度均小於100 位數。
輸出說明:
對每一筆測試資料,輸出相加後有幾次進位的次數。
輸入範例:
2
123 456
555 555
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
For i = 1 To n
Input #1, x, y
ans = 0
a1 = Val(Len(x))
a2 = Val(Len(y))
Do
If a1 > a2 Then
y = "0" & y
Else
x = "0" & x
End If
a1 = Val(Len(x))
a2 = Val(Len(y))
Loop Until a1 = a2
For j = a1 To 1 Step -1
c = Val(Mid(x, j, 1)) + Val(Mid(y, j, 1)) + d
If c >= 10 Then
d = Val(c \ 10)
ans = ans + 1
End If
Next
Print #2, ans
Next
Close
Close
End
End Sub
小冰好,
回覆刪除這題的d一樣有(簡易大數加法)那題中的問題,再改改。
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
For i = 1 To n
Input #1, x, y
ans = 0
a1 = Len(x)
a2 = Len(y)
Do
If a1 > a2 Then
y = "0" & y
Else
x = "0" & x
End If
a1 = Len(x)
a2 = Len(y)
Loop Until a1 = a2
For j = a1 To 1 Step -1
c = Val(Mid(x, j, 1)) + Val(Mid(y, j, 1)) + d
d = Val(c \ 10)
If c >= 10 Then
ans = ans + 1
End If
Next
Print #2, ans
Next
Close
Close
End
End Sub
兩題是從同一個想法出來的,所以程式碼大多也一樣,這樣改過 應該是正確的了,d 每跑一次就重新計算,所以應該不會多加、少加的問題了。
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
For i = 1 To n
ans = 0
Input #1, x, y
a = Len(x)
b = Len(y)
Do Until a = b
If a > b Then
y = 0 & y
Else
x = 0 & x
End If
a = Len(x)
b = Len(y)
Loop
a = Len(x)
For j = a To 1 Step -1
c = 0
c = Val(Mid(x, j, 1)) + Val(Mid(y, j, 1)) + d
d = Val(c \ 10)
If c >= 10 Then
ans = ans + 1
End If
Next j
Print #2, ans
Next i
Close
Close
End
End Sub
Private Sub Form_Load()
回覆刪除Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
For i = 1 To n
Input #1, x, y
a1 = Len(x)
a2 = Len(y)
Do
If a1 > a2 Then
y = 0 & y
Else
x = 0 & x
End If
a1 = Len(x)
a2 = Len(y)
Loop Until a1 = a2
ans = 0
For j = a1 To 1 Step -1
d = 0
c = Val(Mid(x, j, 1)) + Val(Mid(y, j, 1)) + d
d = c Mod 10
If c >= 10 Then ans = ans + 1
Next j
Print #2, ans
Next i
Close #2
Close #1
End
End Sub
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
For i = 1 To n
Input #1, a1, a2
r1 = Len(a1)
r2 = Len(a2)
Do
If r1 > r2 Then
a2 = "0" & a2
Else
a1 = "0" & a1
End If
r1 = Len(a1)
r2 = Len(a2)
Loop Until r1 = r2
Sum = 0
For j = r1 To 1 Step -1
c = Val(Mid(a1, j, 1)) + Val(Mid(a2, j, 1)) + g
g = c \ 10
If g > 0 Then
Sum = Sum + 1
End If
Next j
Print #2, Sum
Next i
Close #1
Close #2
End
End Sub