COBOL程序中MULTIPLY指令行为异常,求原因及解决方法
Hey there! Let's get to the bottom of why your factorial calculations are going wonky after a few steps. The issue boils down to integer overflow caused by your variable's data type being too small.
The Root Cause
Look at how you've defined your Product variable:
05 Product PIC S99 VALUE 1.
PIC S99 means this is a signed 2-digit decimal integer—its maximum possible value is 99, minimum is -99. Let's walk through your calculations to see where this breaks:
- 1 * 6 = 6 (fits in 99, no problem)
- 6 * 5 = 30 (still fine)
- 30 * 4 = 120 (uh-oh! 120 is bigger than 99—this causes an overflow)
- 30 * 3 = 90 (squeaks in right under the 99 limit, so it works)
- 90 * 2 = 180 (way over 99, overflow strikes again)
When COBOL encounters an overflow with fixed-length numeric fields like this, it typically truncates the excess digits (or behaves unpredictably depending on your compiler settings) instead of throwing an error—hence the incorrect results you're seeing.
The Fix
You need to give Product enough space to hold the factorial value you're calculating. For factorial of 6 (which is 720), a 3-digit signed integer would work, but to be safe (and if you want to calculate larger factorials later), use a longer field. For example:
05 Product PIC S9(5) VALUE 1.
S9(5) gives you a signed 5-digit integer, which can hold values up to 99999—plenty of room for 6! (720) and even up to 9! (362880).
Here's the updated working-storage section:
DATA DIVISION. WORKING-STORAGE SECTION. 01 Keeping-Track-Variables. 05 Operand PIC S99 VALUE 0. 05 Product PIC S9(5) VALUE 1.
Run this modified code, and your MULTIPLY operations will all return the correct values.
Quick Note
If you ever need to calculate even larger factorials, you might want to look into COBOL's packed decimal (using COMP-3) or even floating-point types, but for your current use case, expanding the decimal digit count of Product is the simplest and most straightforward fix.
内容的提问来源于stack exchange,提问作者Darth Egregious

