2011年6月20日 星期一

題3 數列的公差或等比

在數列中有等差數列以及等比數列,已知道數列的前四項,請判斷出此數列是等差或者等比數列,並求出公差或等比。

輸入說明:
第一行是數列的數目t(0<= t <=10) 。以下每行均包含四個以空白格開的整數,表示數列的前四項。數列的前四項均為不大於10000的自然數,等比數列的比值也是自然樹。

輸出說明:
對數列的每個數列,輸出兩個欄位,欄位與欄位之間以一個空白隔開,若是等差數列則第一欄輸出A,若為等比數列則第一欄輸出G;第二欄則根據數列的判斷結果,輸出其公差或是等比。

輸入範例:
2
2 4 6 8
2 4 8 16
輸出範例:
A 2
G 2

4 則留言:

  1. Dim P, PP, s
    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, Ti

    For i = 1 To Ti
    Line Input #1, k
    s = Split(k)
    AA = A1(0)
    GG = G1(0)

    If AA = True Then Print #2, "A " & P
    If GG = True Then Print #2, "G " & PP

    Next




    Close
    Close
    End
    End Sub

    Function A1(a)

    Dim ch As Boolean
    ch = True
    P = s(1) - s(0)
    For i = 0 To UBound(s) - 1
    If s(i + 1) - s(i) <> P Then ch = False
    Next
    A1 = ch

    End Function

    Function G1(a)

    Dim ch As Boolean
    ch = True
    PP = s(1) \ s(0)
    For i = 0 To UBound(s) - 1
    If s(i + 1) \ s(i) <> PP Then ch = False
    Next
    G1 = ch

    End Function

    回覆刪除
  2. 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, m
    For i = 1 To m
    Line Input #1, n
    x = Split(n)
    a = False: g = False
    For j = 1 To 2
    g1 = Val(x(i)) - Val(x(i - 1))
    g2 = Val(x(i + 1)) - Val(x(i))
    If g1 <> g2 Then a = True
    Next
    If a = False Then Print #2, "A " & g1
    For j = 1 To 2
    g1 = Val(x(i)) \ Val(x(i - 1))
    g2 = Val(x(i + 1)) \ Val(x(i))
    If g1 <> g2 Then g = True
    Next
    If g = False Then Print #2, "G " & g1
    Next
    Close #1
    Close #2
    End
    End Sub

    回覆刪除
  3. Dim A(4) As Integer
    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, T
    For i = 1 To T
    Input #1, A(1), A(2), A(3), A(4)
    ans = ""
    P = False
    If (A(4) / A(3)) = (A(3) / A(2)) And (A(3) / A(2)) = (A(2) / A(1)) Then ans = ans & "G " & (A(2) / A(1)): P = True
    If P = flase And (A(4) - A(3)) = (A(3) - A(2)) And (A(3) - A(2)) = (A(2) - A(1)) Then ans = ans & "A " & (A(2) - A(1))

    Print #2, ans
    Next i
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  4. arro、緣尉、佑好,
    三個的程式都正確。
    緣尉的程式中,i,j弄錯了,但是,結果應該是正確的。
    還有一個小問題,
    自然數,有沒有包含0呢?
    去查了查wiki,發現都有可能。
    如果包含了0,那麼你們三個的程式中,都會出現"除以零"的錯誤。
    在這兒,先當成沒有包含0吧。但是,以後在看題目,寫程式時,要小心。

    回覆刪除