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

C语言贷款计算程序仅读取首个输入且还款额为0,故障原因是什么?

错误原因

  • scanf函数不支持在格式符中添加.2这类精度控制规则,该语法仅可用于printf输出时指定精度。你的代码中scanf("%.2f",&a)的写法非法,导致第一个输入读取后输入流匹配异常,后续的两个scanf调用全部失效,变量b、c未被正常赋值,最终计算结果全部为0。

修正后代码

#include<stdio.h>
int main(void)
{
    float a, b, c, d, e, f, g;

    printf("enter amount of loan:\n");
    scanf("%f",&a);

    printf("enter interest rate:\n");
    scanf("%f",&b);

    printf("enter monthly payment:\n");
    scanf("%f",&c);

    d=a*(1+b/100.00f);
    e=d-c;
    f=e-c;
    g=f-c;

    printf("balance remaining after first payment:%.2f\n",e);
    printf("balance remaining after second payment:%.2f\n",f);
    printf("balance remaining after third payment:%.2f\n",g);

    return 0;
}

可选优化说明

当前代码的利息计算逻辑为全额年化利息直接计入首月应还,不符合常规贷款按月计息的规则,可根据需求调整为每月剩余本金计算当月利息:

float month_rate = b / 12.0f / 100.0f;
e = a * (1 + month_rate) - c;
f = e * (1 + month_rate) - c;
g = f * (1 + month_rate) - c;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:54:05