Arithmetic/Integer: Difference between revisions
Content added Content deleted
(→{{header|Ruby}}: Also do exponentiation.) |
(→{{header|UNIX Shell}}: SUSv3 says that $(($x)) and $((x)) are alike, so remove the extra dollar signs.) |
||
Line 1,627: | Line 1,627: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
The Unix shell does not directly support arithmetic operations |
The Unix shell does not directly support arithmetic operations, so external tools, such as ''expr'' are used to perform arithmetic calculations when required: |
||
{{works with|Bourne |
{{works with|Bourne Shell}} |
||
{{works with|Almquist SHell}} |
{{works with|Almquist SHell}} |
||
<lang sh>#!/bin/sh |
<lang sh>#!/bin/sh |
||
Line 1,639: | Line 1,639: | ||
echo "a mod b = " `expr $a % $b` # same sign as first operand</lang> |
echo "a mod b = " `expr $a % $b` # same sign as first operand</lang> |
||
Notes: Using the ` (backtick operators, also available in most Bourne shells via the ''$(...)'' syntax) allows us to keep the results on their labels in the most efficient and portable way. The spaces around the operators in the ''expr'' command line arguments are required and the shell requires us to quote or escape the ''*'' character has shown, to prevent any possible "globbing" --- filename expansion of the ''*'' as a wildcard character. |
|||
With SUSv3 parameter expansions: |
With SUSv3 parameter expansions: |
||
Line 1,648: | Line 1,648: | ||
<lang bash>#!/bin/sh |
<lang bash>#!/bin/sh |
||
read a; read b; |
read a; read b; |
||
echo "a+b = $(( |
echo "a+b = $((a+b))" |
||
echo "a-b = $(( |
echo "a-b = $((a-b))" |
||
echo "a*b = $(( |
echo "a*b = $((a*b))" |
||
echo "a/b = $(( |
echo "a/b = $((a/b))" # truncates towards 0 |
||
echo "a mod b = $(( |
echo "a mod b = $((a%b))" # same sign as first operand</lang> |
||
Note: spaces inside the ''$((...))'' are optional and not required; the ''$((...))'' can be inside or outside the double quotes, but the `...` expressions from the previous example can also be inside or outside the double quotes. |
|||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |