C / Variables的Intro打印不正确

w46czmvw  于 2023-11-17  发布在  其他
关注(0)|答案(2)|浏览(124)

这段代码应该从用户那里获取房屋贷款的详细信息,并计算他们在贷款期限内将支付多少钱。我的代码正确地接受了所有输入,但不会在“for”循环中相应地打印它们。我的“Month”变量设置得非常高,其余变量设置为0。我如何才能使代码正常工作
我希望将贷款余额、apr、每月应支付的金额和年数的所有输入,然后计算支付给总余额的金额和支付给利息的金额,并将每个月的金额打印出来,直到最后一个月,打印出全部支付的金额和当前余额。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int years, month, final_month, annual_interest_rate;
    
    double loan_balance, interest_for_this_month, monthly_payment, total_interest, leftover_payment, monthly_interest_rate;
    
    printf("\n\nLoan Amount = ");
    scanf("%lf", &loan_balance);
    printf("%.2lf\n", loan_balance);
    
    printf("\n\nNumber of Years = ");
    scanf("%i", &years);
    printf("%i\n", years);
    
    printf("\n\nAnnual Interest Rate Percent = ");
    scanf("%i", &annual_interest_rate);
    printf("%i\n", annual_interest_rate);
    
    printf("\nMonthly Payment = ");
    scanf("%.2lf", &monthly_payment);
    printf("%.2lf\n", monthly_payment);
    
    monthly_interest_rate = annual_interest_rate/1200;
    
    final_month = years*12;
    //total_interest = 0; 
    
    for(month = 1; month <= final_month; month = month+1)
    { 
        interest_for_this_month = (monthly_interest_rate * loan_balance);
        total_interest = (total_interest + interest_for_this_month);
        leftover_payment = (monthly_payment - interest_for_this_month);
        loan_balance = (loan_balance - leftover_payment);
        printf("Month = (%i),   This month's interest = (%.2lf)   leftover payment = (%.2lf)   Loan Balance = (%.2lf\n\n)"); month, interest_for_this_month, leftover_payment, loan_balance;
        
    }
    
    printf("\nTotal Interest = %.2lf\n", total_interest);
    printf("Final Loan Balance = %.2lf\n\n\n", loan_balance);

    return 0;
}

字符串

jucafojl

jucafojl1#

至少有三个问题:

分公司

annual_interest_rate/1200是一个int除法,其商为int(本例中为0)。double除法使用annual_interest_rate/1200.0

未初始化变量

total_interest未初始化。添加total_interest = 0;@Fe2O3。

**scanf()不支持 * 精度 *

scanf("%.2lf"...中删除".2"以避免未定义行为(UB)。

高级

真实的货币代码将使用十进制浮点数或按100(整数金额 * 美分 *)进行缩放,并对利息计算进行四舍五入以获得精确的货币答案。

k5ifujac

k5ifujac2#

在循环中的printf()行中,);出现在错误的位置。

printf("Month = (%i),   This month's interest = (%.2lf)   leftover payment = (%.2lf)   Loan Balance = (%.2lf\n\n)"); month, interest_for_this_month, leftover_payment, loan_balance;

字符串
可以重新格式化为:

printf("Month = (%i),   This month's interest = (%.2lf)   "
           "leftover payment = (%.2lf)   Loan Balance = (%.2lf\n\n)");
    month, interest_for_this_month, leftover_payment, loan_balance;


最后一行是一系列没有副作用的逗号运算符;你应该得到一个警告。前两行是对printf()的调用,它需要4个值,但没有给出任何值。我已经使用字符串连接来拆分字符串。你的编译器应该抱怨printf()调用和逗号运算符集;如果不是,打开警告选项或使用更好的编译器。
你需要的是:

printf("Month = (%i),   This month's interest = (%.2lf)   "
           "leftover payment = (%.2lf)   Loan Balance = (%.2lf\n\n)",
           month, interest_for_this_month, leftover_payment, loan_balance);

可能还有其他问题,但这就是为什么循环没有打印任何有用的东西。注意其他答案和注解。

相关问题