Gitnik
Gitnik

Reputation: 574

Why does Tcl expr command returns integers by default?

Why does Tcl expr command returns integers by default? I have read the documentation (Section "Types, overflow and precision"), but is there any other way to "make" expr to return float except adding 0.0 to the result and similar?

For example, I'm learning Tcl and I made a simple program to calculate average value:

puts -nonewline stdout "Please enter scores: "
flush stdout;
set score [gets stdin];

set sum 0;
set counter 0;

foreach mark $score {
    set sum [expr {$sum + $mark}];
    incr counter;
}

puts "Your average score is: [expr {$sum/$counter}]";

As an example:

Please enter scores: 1 2 4
Your average score is: 2

Otherwise:

Please enter scores: 1 2 4.0
Your average score is: 2.333333333333335

Is there other way for expr to return float, or do I have to insert 0.0, or *.0 here and there to make sure I get result I want? And why is that so?

Upvotes: 2

Views: 1346

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386030

If any of the numbers in the expression are floats, it will return a float. From the expr man page:

For arithmetic computations, integers are used until some floating-point number is introduced, after which floating-point is used.

So, you can do something like this:

puts "Your average score is: [expr {double($sum)/$counter}]";

Another possibility is to make sure that sum or mark is already a double:

set sum 0.0
...
set sum [expr {$sum + $mark}]

Upvotes: 3

Related Questions