簡體   English   中英

將溫度從攝氏轉換為華氏?

[英]convert temp from Celsius to Fahrenheit?

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

您還可以使用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)
}
#!/bin/bash
read -p "Enter degree celsius temperature: " C
F=`echo "1.8 * $C + 32" | bc`
echo The temperature in Fahrenheit is $F

對於 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)。

僅使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM