problem about the programming language (urgent)

2006-11-25 8:04 pm
here is a program

MAX = -1
For n = 1 to 10
INPUT X
IF X > MAX THEN
MAX = X
ENDIF
NEXT
OUTPUT MAX

The purpose is to find the largest one of 10 the input numbers(integer) input by the user.
However,the final outcome will be -1 if all the 10 input no. are smaller than -1
My question is how to solve this problem so that whatever the user input (integer), the program can still find out the largest one from the 10 input numbers.
Thanks very much

回答 (2)

2006-11-25 10:20 pm
✔ 最佳答案
initialize MAX to the first input. Then run the loop 9 times, and check for a new MAX.


INPUT X
MAX = X
For n = 2 to 10
INPUT X
IF X > MAX THEN
MAX = X
ENDIF
NEXT
OUTPUT MAX
2006-11-25 8:13 pm
有兩個方法:

方法一:將 max 先 declare 成最少的數字。那樣就能確保不會有 integer 比 x 小。不同的 programming language 有不同的 integer 最小值。例如 java,你可以 declare max 做 -2147483648。

MAX = -2147484648
For n = 1 to 10
INPUT X
IF X > MAX THEN
MAX = X
ENDIF
NEXT
OUTPUT MAX

方法二:如另外一個 variable 去檢查是否第一個數字,如果是第一個數字就 assign 做 max 值(因為如果是第一個數字,它一定是 max)。

MAX = -1
FIRST = 0
For n = 1 to 10
INPUT X
IF FIRST = 0 THEN
FIRST = 1
MAX = X
ELSE
 IF X > MAX THEN
 MAX = X
 ENDIF
ENDIF
NEXT
OUTPUT MAX

個人經驗第二種方法較好。因為不會因應不同的 programming language 或 data type(例如 integer 如 long 的最小值不同)而改變。


收錄日期: 2021-04-25 13:05:26
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20061125000051KK01603

檢視 Wayback Machine 備份