bash: divide by zero error and dividing only shows integer answers

时间:2018-09-18 19:58:19

标签: python bash shell

I am writing a simple bash calculator for class and have almost completed it, but I am running into problems with two issues:

  • I am using an if/then argument to try to deal with divide by zero errors. I continue to get an error from this section of the script

  • I use python to return non-integer numbers and it works on all operations except division. I'm not sure why this one specific operation is not working.

I have looked at all the posts it gave me at the top of the screen and I also google queried site:stackoverflow.com for a number of tags and didn't find anything that worked to fix either of these issues. If I'm in the wrong forum or it's already been answered -this is my first time using the site - so I apologize in advance.

Any insight would be most helpful. Thanks in advance!

Here are the sections:

Problem 1: if command returns an error, how would I go about fixing so that it opts out if divide by zero?

if [ $n3 -eq 4 $$ $n2 -eq 0 ]
    then
        echo "Oops, cannot divide by zero. Your answer is undefined."

if

End of first problem.

Problem 2: the below equation does not output non-integer numbers, (e.g. 1 divided by three shows 0, I want it to show 0.333 or similar), why?

    4) 
    quotient=$(python -c "print $n1/$n2")
        echo "The quotient of $n1 and $n2 is $quotient"
            ;;

End of problem area 2.

*)          
        echo "Invalid Option. Pick a number between 1-4 for your operator."
            ;;

esac

1 个答案:

答案 0 :(得分:1)

For your condition, you used [ $n3 -eq 4 $$ $n2 -eq 0 ] where you presumably intended the $$ to be &&. You can do one of:

[ "$n3" -eq 4 ] && [ "$n2" -eq 0 ] # POSIX 
[[ $n3 -eq 4 && $n2 -eq 0 ]]       # Bash specific

For your other problem, see Why does Python return 0 for simple division calculation?. You can do:

n1=1 n2=4
quotient=$(python -c "print $n1.0/$n2")  # Becomes "print 1.0/4"
echo "$quotient"                         # Shows 0.25