C语言大数值处理问题:超int范围输入输出异常如何解决?
Hey there! Let's break down why your code is acting up with big numbers like 1000000000 and how to fix it properly.
The Root Cause
Your current code uses int for variables like m, n, a, and count. The problem is that int has a strict range limit—on most systems, it can only hold values between roughly -2,147,483,648 and 2,147,483,647. When you input values like 1e9 (which is just under the max int value), multiplying two such results (like 1e9 * 1e9) gives 1e18, which is way beyond what an int can store. This causes integer overflow, leading to garbage or incorrect output.
The Fix: Switch to 64-bit Integers
To handle numbers up to 1e9 * 1e9, you need to use a 64-bit integer type. In C, that's long long—it can hold values up to 9,223,372,036,854,775,807, which is more than enough for your input range.
Here are the key changes to implement:
- Replace all
intdeclarations withlong longfor variables involved in calculations. - Update the
scanfformat specifiers from%dto%lld(sincelong longuses this format code in standard C). - Simplify your tile-counting logic: instead of using conditional checks for remainders, use the formula
(x + a - 1) / ato calculate the ceiling ofx/ain one line. This trick works because addinga-1ensures any remainder pushes the value up to the next integer when divided.
Modified Code
#include<stdio.h> int main() { long long m, n, a; long long count = 1; scanf("%lld%lld%lld", &m, &n, &a); // Calculate ceiling of m/a and n/a, then multiply count *= (m + a - 1) / a; count *= (n + a - 1) / a; printf("%lld\n", count); return 0; }
Why This Works
- Using
long longensures even the product of two1e9values (1e18) fits comfortably within the variable's range. - The simplified formula
(x + a - 1)/aeliminates messy if-else checks:- If
xis divisible bya:(x + a -1)/a = (k*a +a-1)/a = k(integer division truncates the fractional part, giving the correct quotient). - If
xisn't divisible bya:(x +a-1)/a = (k*a + r +a-1)/awhere0 < r <a. Sincer+a-1 >=a, this becomesk+1—exactly the ceiling value we need.
- If
Test with Your Example
For input 1000000000 1000000000 1, the code calculates (1e9 +1-1)/1 =1e9 for both dimensions, multiplies to get 1e18, and prints it correctly without overflow.
内容的提问来源于stack exchange,提问作者oldMCdonald

