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

C语言个税计算代码使用float类型乘法仍输出0问题咨询

问题成因
  • C语言中两个整数常量做除法运算时,会执行整数除法规则,直接舍弃结果的小数部分,仅保留整数部分。你代码中写的5 / 100、20 / 100、30 / 100都属于整数运算,运算结果均为整数0,后续乘以float类型的收入变量,最终计算结果自然也为0,和收入变量是否为float类型无关。
修复方案

任选以下任意一种方案修改税费计算逻辑即可:

  1. 将除法运算的其中一个操作数改为浮点常量,触发浮点除法,比如修改为5.0 / 100、20.0 / 100、30.0 / 100
  2. 直接使用对应比例的浮点数值替换除法运算,比如0.05、0.2、0.3,运算效率更高也更易读
  3. 对其中一个整数操作数强制转换为浮点类型,比如(float)5 / 100
修复后参考代码
#include <stdio.h>

int main()
{
    float income;
    printf("enter your annual income here:");
    scanf("%f", &income);
    if (income < 250000)
    {
        printf("no income tax");
    }
    else if (income >= 250000 && income < 500000)
    {
        printf("your income tax will be:%f", 0.05 * income);
    }
    else if (income >= 500000 && income < 1000000)
    {
        printf("your income tax will be:%f", 0.2 * income);
    }
    else if (income >= 1000000)
    {
        printf("your income tax will be:%f", 0.3 * income);
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者Ayush kumar Rai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:15:02