BLACK CAT PROGRAMMER

BASH – Calculating average

原來之前都幾無聊下,寫左咁多「小方遊戲」

#!/bin/bash

# cal_avg.sh
# Calculate the average of a series of numbers.

SCORE="0"
AVERAGE="0"
SUM="0"
NUM="0"

while true; do

  echo -n "Enter your score [0-100%] ('q' for quit): "; read SCORE;

  if (("$SCORE" < "0"))  || (("$SCORE" > "100")); then
    echo "Be serious.  Common, try again: "
  elif [ "$SCORE" == "q" ]; then
    echo "Average rating: $AVERAGE%."
    break
  else
    SUM=$[$SUM + $SCORE]
    NUM=$[$NUM + 1]
    AVERAGE=$[$SUM / $NUM]
  fi

done

echo "Exiting."
Posted in notesTagged

BASH – Guess number

Bash small game

#!/bin/bash

ANSWER=$[$RANDOM%100+1]
GUESS="-1"
FROM="1"
TO="100"

echo "The ANSWER is $ANSWER"

while true; do

	echo -n "Please guess a number [$FROM-$TO]: "; read GUESS;
	if (("$GUESS" < "$TO")) && (("$GUESS" > "$FROM")); then
		if (("$ANSWER" < "$GUESS")); then
			TO=$GUESS;
		elif (("$ANSWER" > "$GUESS")); then
			FROM=$GUESS;	
		elif (("$ANSWER" == "$GUESS")); then
			break
		fi
	else
		echo "Please enter again";
	fi
done

echo "Bingo. The answer is $ANSWER";
Posted in notesTagged