- Prepare
- Linux Shell
- Bash
- Arithmetic Operations
- Discussions
Arithmetic Operations
Arithmetic Operations
+ 0 comments read -p "Enter the expression: " exp printf "%.3f" $(echo $exp | bc -l)
where 1st line will take the expression, and 2nd line will read the expression using echo $exp, perform the calculations using bc -l and print the result upto 3 decimal places using printf "%.3f"
+ 0 comments read x var=$(echo "scale=4; $x" | bc) printf "%.3f\n" "$var"
+ 0 comments The simplest solution:
printf "%0.3f" $(cat - | bc -l)
cat -
reads a numeric value from standard input (stdin).|
pipes the input to the next command.bc -l
performs arbitrary-precision calculations, including math functions like sine and cosine.$(...)
captures the result of thebc
calculation.printf "%0.3f"
formats and prints the captured result as a floating-point number with three decimal places.In summary, this code reads a number, performs a mathematical operation, and displays the result with three decimal places.
+ 0 comments read number new_number1=$( echo "scale=4; $number " | bc) new_number2=$( echo "scale=3; $number " | bc) last1=${new_number1: -1} last2=${new_number2: -1} if(( last1 < 5)); then echo $new_number2 else if(( last2 < 9 )); then last2=$((last2+1)) fi new_number2=${new_number2:0:-1}$last2 echo $new_number2 fi
+ 0 comments read expression
result= expression" |bc )
echo $result
Sort 218 Discussions, By:
Please Login in order to post a comment