You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言大数值处理问题:超int范围输入输出异常如何解决?

How to Fix Your C Code for Large Numeric Inputs

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 int declarations with long long for variables involved in calculations.
  • Update the scanf format specifiers from %d to %lld (since long long uses this format code in standard C).
  • Simplify your tile-counting logic: instead of using conditional checks for remainders, use the formula (x + a - 1) / a to calculate the ceiling of x/a in one line. This trick works because adding a-1 ensures 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 long ensures even the product of two 1e9 values (1e18) fits comfortably within the variable's range.
  • The simplified formula (x + a - 1)/a eliminates messy if-else checks:
    • If x is divisible by a: (x + a -1)/a = (k*a +a-1)/a = k (integer division truncates the fractional part, giving the correct quotient).
    • If x isn't divisible by a: (x +a-1)/a = (k*a + r +a-1)/a where 0 < r <a. Since r+a-1 >=a, this becomes k+1—exactly the ceiling value we need.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:35:28