Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expected integer but got "floating point number" error

Tags:

tcl

I try to write a very simple program in TCL using list.

Below is the list

list { 1 2 3 4 5 6 1.5 7 }

Below is my code

set sum 0
for {set i 0} {$i < [llength $list]} {incr i} {
    incr sum [lindex $list $i]
}

puts  $sum

On executing the above program I am getting the below error due to floating point value of 1.5 in the list

expected integer but got "1.5"
    (reading increment)
    invoked from within
"incr sum [lindex $list $i]"

I searched on internet and could not find anything relevant. Please advise how do I handle the floating point value?

like image 319
user3739573 Avatar asked Jun 11 '26 15:06

user3739573


1 Answers

While using incr command, variable must have value that can be interpreted as a an integer. See tcl wiki. If variable is a non-integral real number, [incr] could not be used, but [set] could:

set sum 0
for {set i 0} {$i < [llength $list]} {incr i} {
    set sum [expr {$sum + [lindex $list $i]}]
}

puts  $sum
like image 77
Omsai Jadhav Avatar answered Jun 15 '26 06:06

Omsai Jadhav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!