Home | Tech Database | Tech BBS | White Papers | Purchase

## Dividing Integers example

Keywords: Division Divide Integer example problem

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.

Example:

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)

Article ID:W13032Filename:Dividing Integers example.txt