Microsoft KB Archive/62264

COBOL Cannot Perform Integer Division Within COMPUTE

PSS ID Number: Q62264 Article last modified on 05-29-1990

3.00 3.00a | 3.00 3.00a MS-DOS | OS/2

Summary: The COMPUTE statement does not truncate intermediate values when it is doing a division operation within an expression involving variables that cannot contain decimal places. In other words, there is no way to perform “integer division” within an expression. Truncation is only performed on the final result before it is assigned to a receiving data item. This information applies to Microsoft COBOL Compiler versions 3.00 and 3.00a for MS-DOS and MS OS/2.

More Information: Other programming languages provide an operator to perform what is called “integer division”: dividing two numbers and discarding (truncating) the fractional remainder. COBOL does not have this feature. Integer division must be simulated by assigning the result of the division to a data item that does not store decimal places. This will effectively truncate the result, but does not allow for integer division in the middle of an expression, which can make some calculations tedious. The following program (COMPUTE.CBL) illustrates how COMPUTE handles truncation when doing division with numbers that are whole, that is, numbers whose PICTURE clauses do not allow for decimal places. To compile and link the program, use the following: cobol compute; link compute;

Code Example
$SET ANS85 DATA DIVISION. WORKING-STORAGE SECTION. * All three of these data items cannot contain digits to the * right of the decimal place. 01 DATA-ITEM  PIC 9. 01 TWO        PIC 9 VALUE 2. 01 THREE      PIC 9 VALUE 3. PROCEDURE DIVISION. *   Even though only whole numbers are involved in the *   calculation, COMPUTE will retain the value 1.5 when it  *    processes (THREE / TWO) instead of truncating it to 1. *   Thus the final result to be put in DATA-ITEM will be 3. COMPUTE DATA-ITEM = (THREE / TWO) * TWO. DISPLAY DATA-ITEM. *   Here, when THREE / TWO is assigned to DATA-ITEM, it is  *    truncated to 1 first. So the final result in DATA-ITEM *   is 2 instead of 3. COMPUTE DATA-ITEM = THREE / TWO. COMPUTE DATA-ITEM = DATA-ITEM * TWO. DISPLAY DATA-ITEM. The output of the program is as follows: 3 2

Copyright Microsoft Corporation 1990.