Dividing Floating Point Numbers

 

This example might not work exactly how you think it will. If you take two integers, for example, 32 and 37, and divide 32 by 37, you will not necessarily get a floating point answer. This integer divide will result in an answer of 0. Add 0.0 to one of the numbers to get a true floating point answer.


§         Notes

§         Reference

§         Step by step guide to learning WIL

 

Example:
;;Problem.wbt
a1= "An unexpected problem can occur when dividing numbers."
a2= "The problem is in deciding between an integer divide "
a3= "(where the remainder, if any, is discarded) and a floating "
a4= "point divide (where a floating point number is returned)."
a5= ""
a6= ""
a7= "Let's assume a test. There are 42 questions."
a8= "A student gets 37 of them correct,"
a9= "what is the student's score."
a10= " "
a11= "iQuestions = 42"
a12= "iCorrect = 37"
a13= "Score = iCorrect / iQuestions"
iQuestions = 42
iCorrect = 37
Score = iCorrect / iQuestions

a14= " " a15= "The unexpected result is that the score is %Score%" a16= "Reasonable problem? The trap is that WIL will perform an" a17= "integer divide and return the unexpected answer of Zero." a18= " " a19= "To dig your code out of this trap, simply use floating point" a20= "numbers when you want a floating point answer." a21 = " " a22= "fQuestions = 42.0" a23= "fCorrect = 37.0" fQuestions = 42.0 fCorrect = 37.0 Score = fCorrect / fQuestions
a24= "Score = fCorrect / fQuestions" a25= "The correct score is %Score%" a26= " " a27= "Or make the answer look nicer by using the Decimals function" a28= "and a little formatting." a29= "" a30= "Decimals(0)" a31= "Score=Score*100" Decimals(0) Score=Score*100 a32= "" a33= "The correct score is %Score%%%"
text="" For i=1 To 15 text=StrCat(text,a%i%,@crlf) Next
text2="" For i=16 To 33 text2=StrCat(text2,a%i%,@crlf) Next
Message("Integer Divide Problem",text) Message("Floating point solution",text2)