返回列表 發帖

402 字串與檔案處理 (字串比較)

1. 題目說明:
請依下列題意進行作答,使輸出值符合題意要求。

2. 設計說明:
請撰寫一程式,讓使用者輸入兩個相同長度的字串與一個正整數n,字串長度皆不超過128個字元,依ASCII碼表上的順序比對兩字串前n個字元,最後輸出兩字串前n個字元的比較結果。若使用者輸入正整數n超過字串長度,則輸出「error」。

提示:若使用 Java 語言答題,請以「JP」開頭命名包含 main 靜態方法的 class,評測系統才能正確評分。

3. 輸入輸出:
輸入說明
兩個相同長度的字串及一個正整數

輸出說明
兩字串前n個字元的比較結果(大於、等於、小於)

範例輸入1
Apple ipad
Apple ipod
5

範例輸出1
Apple ipad = Apple ipod

範例輸入2
Apple ipad
Apple ipod
9

範例輸出2
Apple ipad < Apple ipod

範例輸入3
Apple ipad
Apple ipod
15

範例輸出3
error

本帖隱藏的內容需要回復才可以瀏覽
Python
  1. str1 = input()
  2. str2 = input()
  3. n = int(input())
  4. compare = 0

  5. if n > len(str1):
  6.     print('error')
  7.     exit()

  8. for i in range(n):
  9.     compare += ord(str1[i]) - ord(str2[i])

  10. if compare > 0:
  11.     print(str1 + ' > ' + str2)
  12. elif compare < 0:
  13.     print(str1 + ' < ' + str2)
  14. else:
  15.     print(str1 + ' = ' + str2)
複製代碼
[/hide]
istak.teach2@gmail.com

此帖僅作者可見

TOP

此帖僅作者可見
(☆▽☆)<<可以按喔

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

返回列表