Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

HackerRank Arithmetic Operations problem solution

YASH PAL, 31 July 2024

In this HackerRank Arithmetic Operations problem solution A mathematical expression containing +,-,*,^, / and parenthesis will be provided. Read in the expression, then evaluate it. Display the result rounded to 3 decimal places.

Constraints

All numeric values are <= 999.

HackerRank Arithmetic Operations problem solution

Problem solution.

read line
ans1=`(echo "scale = 4; ($line)" | bc)`
IFS='.' read -a fnum <<< "$ans1"
dig="${fnum[1]:3}"
mantissa=`echo "${fnum[1]}" |cut -c1-3`
if [ "$dig" -ge "5" ]
then
    mantissa=$((mantissa+1))
fi
ans=${fnum[0]}$"."$mantissa
echo $ans

Second solution.

read line
val=`echo "$line" | bc -l`
if [ `echo "$val < 0.0" | bc` -eq 1 ]; then
    echo "scale = 3; ($val - 0.0005) / 1.0" | bc -l
else
    echo "scale = 3; ($val + 0.0005) / 1.0" | bc -l
fi

Third solution.

#!/bin/bash
# your code goes here
read n
printf "%.3fn" $(bc -l <<< $n)

Fourth solution.

read expr
value=$(echo "$expr" | bc -lq)
printf '%.3f' $value

coding problems linux shell

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes