Reputation: 27
my task was to print whether the numbers given signify ISOSCELES,EQUILATERAL, or SCALENE triangle. My code prints only ISOSCELES: Where's the error ?
#!/bin/bash
read a b c
if [ "$a" == "$b" ] && { [ "$b" = "$c" ] && [ "$c" = "$a" ]; }
then
echo "EQUILATERAL"
exit 1
elif [ "$a" == "$b" ] && { [ "$b" = "$c" ] || [ "$c" = "$a" ]; }
then
echo "ISOSCELES"
elif ([[ "$a" != "$b" ]] && [[ "$b" != "$c" ]] && [[ "$c" != "$a" ]])
then
echo "SCALENE"
fi
Upvotes: 0
Views: 591
Reputation: 117
Take the sides of traingles as input using read command.
read a
read b
read c
if (( a == b )) && (( b == c )) && (( c == a ));
then
echo "EQUILATERAL"
elif (( a != b )) && (( b != c )) && (( c != a ));
then
echo "SCALENE"
else
echo "ISOSCELES"
fi
Upvotes: 0
Reputation: 25023
==
and =
in your testsUpvotes: 1
Reputation: 241828
You can just count the number of different numbers to get the answer.
#!/bin/bash
read a b c
different=$(printf '%s\n' $a $b $c |
sort -n |
uniq -c |
wc -l
)
case $different in
(1) echo EQUILITERAL ;;
(2) echo ISOSCELES ;;
(3) echo SCALENE ;;
esac
You should also verify the triangle inequality at the beginning:
#!/bin/bash
read a b c
sorted=$( printf '%s\n' $a $b $c | sort -n )
ineq=${sorted/$'\n'/+}
ineq=${ineq/$'\n'/>}
(( $ineq )) || exit 1
different=$( uniq -c <<< "$sorted" | wc -l )
case $different in
(1) echo EQUILITERAL ;;
(2) echo ISOSCELES ;;
(3) echo SCALENE ;;
esac
Upvotes: 2
Reputation: 9282
That a bit simplified:
#!/bin/bash
read a b c
if [ "$a" -eq "$b" ] && [ "$b" -eq "$c" ] && [ "$c" -eq "$a" ];
then
echo "EQUILATERAL"
exit 1
elif [ "$a" -ne "$b" ] && [ "$b" -ne "$c" ] && [ "$c" -ne "$a" ];
then
echo "SCALENE"
else
echo "ISOSCELES"
fi
I think thats the purposed output:
$ echo "6 6 6" | ./script
EQUILATERAL
$ echo "6 6 5" | ./script
ISOSCELES
$ echo "4 5 6" | ./script
SCALENE
Upvotes: 0
Reputation: 74595
There's a strange mixture of [
, [[
, =
and ==
in your script. If you are using bash, I would suggest that you instead use (( ))
for all of your numerical comparisons. This creates an arithmetic context, so it also means that you don't need to use $
to refer to your variables:
if (( a == b )) && (( b == c )) && (( c == a )); then echo "equilateral"
elif (( a != b )) && (( b != c )) && (( c != a )); then echo "scalene"
else echo "isoceles"
fi
The separate test for isosceles is unnecessary.
Upvotes: 2
Reputation: 37023
Try (use == or -eq for numbers):
#!/bin/bash
read a b c
if [ "$a" == "$b" ] && { [ "$b" == "$c" ] && [ "$c" == "$a" ]; }
then
echo "EQUILATERAL"
elif ([[ "$a" != "$b" ]] && [[ "$b" != "$c" ]] && [[ "$c" != "$a" ]])
then
echo "SCALENE"
else
echo "ISOSCELES"
fi
Upvotes: 0