0

この USD から SEK への通貨コンバーターと空の行、行 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
4

1 に答える 1

1

You can do floating point arithmetic using bc like this:

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

Explanation:

Bash does not have built it support for floating point arithmetic. Thus, we usually handle these operation using the bc program. bc reads an arithmetic expression as a string from the standard input, and prints the result the standard output. Note that the -l option is necessary for keeping the decimal part of the expression.

In order to get the result from bc, and store it in a variable, we use command redirection i.e. the $( ). Note that there are no spaces before and after the = in the previous expression.

Complete Example

#!/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

Output

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

Note that i removed the declare -i SEK from the script, since the SEK variable is NOT Integer

The harm of declare -i. This code produces:

#!/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"

This output:

$ ./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

于 2013-02-14T16:15:54.937 に答える