#!/bin/bash
read -p "Enter degree celsius temperature: " C
F=$(1.8*{$C}) 32
echo The temperature in Fahrenheit is $F
在上面的 shell 腳本中,我試圖將溫度從攝氏溫度轉換為華氏溫度
收到此錯誤
/code/source.sh: line 3: 1.8 {32}: command not found 華氏溫度為 32 *
答案應該是 89
uj5u.com熱心網友回復:
您還可以awk用于浮點計算,并且可以使用以下命令控制輸出格式printf:
#!/bin/bash
read -p "Enter degree celsius temperature: " c
awk -v c="$c" 'BEGIN {printf("The temperature in Fahrenheit is %.2f\n", 1.8 * c 32)}'
或者我們可以卸下bash零件并找到awk唯一的解決方案
#!/usr/bin/awk -f
BEGIN {
printf("Enter degree celsius temperature "); getline c;
printf("The temperature in Fahrenheit is %.2f\n", 1.8 * c 32)
}
uj5u.com熱心網友回復:
#!/bin/bash
read -p "Enter degree celsius temperature: " C
F=`echo "1.8 * $C 32" | bc`
echo The temperature in Fahrenheit is $F
uj5u.com熱心網友回復:
僅使用 bash,精度為 0.1:
$ cat c2f
#!/usr/bin/env bash
declare -i C F
read -p "Enter degree celsius temperature: " C
F=$(( 18 * C 320 ))
echo "The temperature in Fahrenheit is ${F:0: -1}.${F: -1: 1}"
$ ./c2f
Enter degree celsius temperature: 32
The temperature in Fahrenheit is 89.6
如果您對小數部分不感興趣,但想要四舍五入到最接近的整數:
$ cat c2f
#!/usr/bin/env bash
declare -i C F
read -p "Enter degree celsius temperature: " C
F=$(( 18 * C 325 ))
echo "The temperature in Fahrenheit is ${F:0: -1}"
$ ./c2f
Enter degree celsius temperature: 32
The temperature in Fahrenheit is 90
uj5u.com熱心網友回復:
對于 32 (°C),您的公式1.8*32 32應該產生 89.6 (°F),但正如您提到的Ans 應該是 89,所以我們會忘記小數并使用$((180*$c/100 32)),所以您的程式變為(未經測驗):
#!/bin/bash
read -p "Enter degree celsius temperature: " c
f=$((180*$c/100 32))
echo The temperature in Fahrenheit is $f
輸出:
89
基本上 Bash 不允許您使用小數 (1.8),但您可以將其替換為分數(180/100 或 18/10 甚至 9/5,請參閱評論)。Bash 可以用它來計算,但你會丟失小數(89.6 -> 89)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485023.html
