Arithmetic/Integer: Difference between revisions

→‎{{header|Tcl}}: Minor revisions
(→‎{{header|Tcl}}: Minor revisions)
Line 696:
 
=={{header|Tcl}}==
<lang tcl> puts "Please enter two numbers:"
gets stdin x
gets stdin y
puts "
$x + $y = [expr {$x + $y}]
$x - $y = [expr {$x - $y}]
$x * $y = [expr {$x * $y}]
$x / $y = [expr {int($x / $y)}]
$x mod $y = [expr {$x % $y}]
exponents: $x 'to the' $y = [expr {pow($x,$y)}] (a float) = [expr {$x ** $y}] (an integer)
"</lang>
 
set x [expr {int([gets stdin])}]; # Force integer interpretation
Since Tcl doesn't really know about the "type" of a variable, the "<tt>expr</tt>" command is used to declare whatever follows as an "expression". This means there is no such thing as "integer arithmetic" and hence the kludge <tt>int( $x / $y )</tt>.
set y [expr {int([gets stdin])}]; # Force integer interpretation
 
puts "$x + $y = [expr {$x + $y}]"
puts "$x - $y = [expr {$x - $y}]"
puts "$x * $y = [expr {$x * $y}]"
puts "$x / $y = [expr {int($x / $y)}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]"</lang>
 
Since Tcl doesn't really know about the "type" of a variable, the "<tt>expr</tt>" command is used to declare whatever follows as an "expression". This means there is no such thing as "integer arithmetic" and hence the kludge with <tt>int( $x / $y [gets&nbsp;stdin])</tt>.
 
Often, these operations would be performed in a different way from what is shown here. For example, to increase the variable "x" by the value of the variable "y", one would write
 
<lang tcl>incr x $y</lang>
 
Also, it's important to surround the arguments to the <code>expr</code> in braces, especially when any of the parts of the expression are not literal constants. Discussion of this is on [http://wiki.tcl.tk/10225 hereThe Tcler's Wiki].
 
=={{header|Toka}}==
Anonymous user