【问题标题】:Currency converter货币换算
【发布时间】:2014-01-05 04:54:55
【问题描述】:

我卡在这个美元到瑞典克朗的货币转换器和空行,第 12 行。当前的转换是 1 SEK = 0.158193 USD 1 USD = 6.32138 SEK。

第 12 行的内容类似于 SEK="(?(USD) )?"

我不知道在问号中输入什么。

#!/bin/bash

shopt -s -o nounset
declare -i USD # USD
declare -i SEK # SEK
# Title
printf "%s\n" "USD-SEK Currency Convertor"
printf "\n"
# Get the value to convert
read -p "Enter a USD: " USD
# Do the conversion

printf "You will get SEK %d\n" "$SEK"
exit 0

【问题讨论】:

标签: bash


【解决方案1】:

您可以像这样使用bc 进行浮点运算:

SEK=$( echo " 6.32138 * $USD " | bc -l )

解释:

Bash 不支持 浮点 算术。因此,我们通常使用bc 程序来处理这些操作。 bc 从标准输入读取算术表达式作为字符串,并将结果打印到标准输出。请注意,-l 选项对于保留表达式的小数部分是必需的。

为了从bc 获取结果并将其存储在变量中,我们使用命令重定向,即$()。注意前面表达式中= 前后没有空格。

完整示例

#!/bin/bash
printf "%s\n" "USD-SEK Currency Convertor"
# Get the value to convert
read -p "Enter a USD: " USD
SEK=$(echo " 6.32138 * $USD " | bc -l )
printf "You will get SEK %s\n" "$SEK"  ;#  NOTE THAT I CHANGED THIS TO %s FROM %f DUE TO THE LOCALE SETTINGS

输出

$ ./converter.sh 
USD-SEK Currency Convertor
Enter a USD: 10
You will get SEK 63.213800

请注意,我从脚本中删除了 declare -i SEK,因为 SEK 变量是NOT整数

declare -i的危害。此代码产生:

#!/bin/bash
declare -i SEK     ;#    WOOOPS I FORGOT THE declare -i
printf "%s\n" "USD-SEK Currency Convertor"
# Get the value to convert
read -p "Enter a USD: " USD
SEK=$(echo " 6.32138 * $USD " | bc -l )
printf "You will get SEK %s\n" "$SEK"

这个输出:

$ ./converter.sh 
USD-SEK Currency Convertor
Enter a USD: 10
./converter.sh: line 6: 63.21380: syntax error: invalid arithmetic operator (error token is ".21380")
You will get SEK 0.000000

【讨论】:

  • 我试过这个 SEK="(1*(USD) )*6" 但是如果我想使用6后的小数,我不知道如何声明它?您的示例也是如此,我收到语法错误。 6.32138
  • 好的,谢谢,所以我应该在 printf 中更改为 %f:%f(或 %F)——显示不带指数符号的浮点数
  • 是的,你也应该删除declare -i
  • 这是我运行脚本时得到的:USD-SEK Currency Converter Enter a USD: 10 ./test2.sh: row 6: printf: 63.21380: invalid number You will get SEK 0,000000
  • 在你改成 %f 之前是这样吗?
猜你喜欢
  • 2012-03-15
  • 1970-01-01
  • 2020-08-29
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 2016-04-01
相关资源
最近更新 更多