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

C语言中tax变量无法赋值为新值的问题排查

问题分析与修复方案

核心问题:整数除法导致计算结果为0

C语言中,整数除以整数会执行整数除法,直接舍弃小数部分。你代码里的20/100、15/100、10/100、5/100计算结果都是0,所有和这些值相乘的部分最终都为0,这就是tax始终无法累加出正确数值的根本原因。

其他关键问题

  • 变量类型不匹配:inc、ti、tf存储的数值较大(如3600000、9000000),int类型虽暂时能容纳,但后续计算易溢出,建议改用long long;同时scanf("%ld", &inc)中%ld对应long类型,和int类型的inc不匹配,会导致输入读取错误。
  • 税率计算逻辑错误:第一个if分支里(ti + 18000000)应为(ti - 18000000),超额累进税是对超出起征点的部分征税,而非相加。

修复后的代码

#include <stdio.h>

int main() {
    long long inc;
    long long ti;
    long long tf;
    int n;
    long long tax = 0;
    const long long pd = 3600000;
    const long long pa = 9000000;
    
    printf("Your income of this year: ");
    scanf("%lld", &inc);
    
    printf("\nNumber of dependent: ");
    scanf("%d", &n);
    
    tf = 12 * (pa + n * pd);
    ti = inc - tf;
    
    printf("Tax-free income: %lld\n", tf);
    printf("Taxable income: %lld\n", ti);
    
    if (ti <= 0) {
        printf("\nIncome tax: 0");
        return 0;
    }
    
    if (ti > 18000000) {
        tax += (ti - 18000000) * 0.2;
        ti = 18000000;
    }
    if (ti > 10000000) {
        tax += (ti - 10000000) * 0.15;
        ti = 10000000;
    }
    if (ti > 5000000) {
        tax += (ti - 5000000) * 0.1;
        ti = 5000000;
    }
    tax += ti * 0.05;
    
    printf("\nIncome tax: %lld\n", tax);
    return 0;
}

修复说明

  • 将税率改为浮点数(如0.2代替20/100),确保除法得到正确的小数结果;
  • 把大数值变量替换为long long类型,避免溢出和输入输出不匹配问题;
  • 修正第一个分支的计算逻辑,符合超额累进税的规则;
  • 简化条件判断(如ti > 10000001改为ti > 10000000),因为前序分支已处理完更高区间的税额,无需额外加1。

内容的提问来源于stack exchange,提问作者Im_new

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:35:26