数学复习计划

数学复习计划

我创建了一个程序,它将从一个范围中随机选择两个数字,并从中提出乘法问题。看起来非常凌乱和重复。

我想要的帮助是“如何使我的代码更少重复且更易于理解”这是我的代码...... https://gist.github.com/anonymous/fa95b8493ef4d495f49a

答案1

您可以使用循环来消除重复性for。看https://www.gnu.org/software/bash/manual/html_node/Looping-Constructs.html

这是我想出的:

#!/bin/bash
read -p "Input the range you want to practice. For example: 1-12, 4-9, 9-11: " range

QUESTIONS=0
CORRECT=0

for i in {1..5}; do
  let QUESTIONS++
  n1=$(shuf -i $range -n 1)
  n2=$(shuf -i $range -n 1)
  realans=$((n1 * n2))
  read -p "${n1} x ${n2}? " ans
  if [[ $ans -eq $realans ]]; then
    let CORRECT++
    echo "Correct! ${n1} x ${n2} is ${realans}."
  else
    echo "Incorrect. ${n1} x ${n2} is ${realans}."
  fi
done

echo "You got ${CORRECT} out of ${QUESTIONS} questions correct!"

read为了简单起见,我简化了程序并选择zentity将输入和输出都保留在终端中。我还演示了let var++它的用法,这是一种更干净、更现代的递增计数器的方法。

相关内容