本文介绍了在Unix中提示用户输入两个数字以进行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个脚本,该脚本将提示用户输入两个数字,以厘米为单位表示矩形的宽度和高度,并以平方厘米和平方英寸的形式输出矩形的面积。在Unix中(一英寸= 2.54厘米)。

I want to write a script which will prompt the user for two numbers, representing the width and height of a rectangle in centimetres and output the area of the rectangle in both square centimetres and square inches. In Unix ( one inch = 2.54 centimetres).

我认为它类似于:

echo "Please enter the width:"
read width

echo "Please enter the second height"
read height

ANS=`expr width \* height`
echo "$ANS"

任何帮助将不胜感激

推荐答案

短一个:)

#!/bin/bash
read -p "Width  in cm (default 1)? " w
read -p "Height in cm (default 1)? " h
read acm ain <<<$(dc<<<"5k${w:-1}sa${h:-1}sb2.54silalb*sclcli/li/sdlcps.ldps.q")
echo "width: ${w:-1}(cm), height: ${h:-1}(cm) - Area: $acm (sqcm) $ain (sqin)"

编辑:添加了说明

dc 是计算器,然后执行下一个

the dc is RPN calculator, and doing the next


  • 将精度设置为5

  • 数字$ w(如果不是se t 1)存储到 a

  • 将$ h存储到 b

  • 2.54存储到i

  • 取 a取 b,并将结果存储乘以 c

  • 取 c取 i并除,再次取 i除,再存储结果为 d

  • 取 c并打印

  • 取 d并打印

  • 退出

  • set precision to 5
  • number $w (if not set 1) store to "a"
  • number $h store to "b"
  • 2.54 store to i
  • take "a" take "b" and multiply result store to "c"
  • take "c" take "i" and divide, again take "i" divide again, store the result to "d"
  • take "c" and print
  • take "d" and print
  • quit

在正常数学中:

a=$w; b=$h; i=2.54; c=a*b; d=c/i/i ; print c; print d

和脚本,


  • << 是单行 heredoc- dc 将从标准输入中读取它作为输入

  • $(commnad)意思是:用命令的结果替换$(命令)

  • read xy<< 表示将两个值读入变量x和y( dc 返回2个值)

  • <<< is the one-line "heredoc" - dc will read it as its input from stdin
  • $(commnad) mean: replace the $(command) with the result of the command
  • read x y <<< mean read two values into the variable x and y (the dc returns 2 values)

这篇关于在Unix中提示用户输入两个数字以进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:18