C:For Loop没有初始化,任何想法

时间:2018-02-21 20:53:28

标签: c

  • 嗨,我正在尝试创建一个贷款回收计划,允许用户输入贷款金额,APR%,每月付款,然后输入'For循环'来运行程序,直到贷款金额达到0(每个循环)将减去每月付款),然后更新当前贷款。
  • CurrentLoan将与LoanAmount相同,然后按月付款金额更改。 它只打印出CurrentLoan代码的1行并停止,有人知道为什么吗?

void main()
{
    float LoanAmount;
    float APR;
    float Monthly; /*Prompts Number to a Float characrter type*/
    float DailyInt;
    float OutstandingLoan;
    float CurrentLoan;
    int i, Day, Month, Year;

    i = 0;
    Day = 0; /* Day = 1 Day */
    Month = Day * 30; /* 30 days per month = Month * 30 days*/
    Year == Month * 12; /* 12 months per yar * 30 days per month */

    printf(" Please enter in the Loan Amount : \n\r"); /*prompts user to enter float*/
    scanf("%f", &LoanAmount);

    printf("Please enter in the interest rate as a precentage per year (APR) : \n\r");
    scanf("%f", &APR);

    printf("Please enter in the Monthly payment plan : \n\r");
    scanf("%f", &Monthly);

    printf("\nPerforming calculation using a loan of Loan Amount: %.2f \n\r", LoanAmount);
    printf("with a monthly payment of : %.0f \n\r", Monthly);
    printf("and an APR rate of : %.2f \n\r", APR);

    printf("\n Month \ | Year \ | Current Loan \ | Daily Interest \| total Interest\n\r");

    for (CurrentLoan = LoanAmount; CurrentLoan == 0; ++CurrentLoan); 
    {
        CurrentLoan += Monthly;
        printf("%.2f \n\r", CurrentLoan);               
    };
    return(0);  
}

2 个答案:

答案 0 :(得分:1)

要回答您的具体问题,为什么它只打印一次,这是因为您的print语句不在循环中。

for (CurrentLoan = LoanAmount; CurrentLoan == 0; ++CurrentLoan); // <-- this semicolon is the problem

分号将你的作用域括号与循环分开,所以基本上你是循环并且什么也不做,然后当你完成循环时,你会进行算术和打印。

答案 1 :(得分:0)

一些问题 - 超出一年==天......:

  • for循环将CurrentLoan初始化为例如。 5000,并且只要CurrentLoan == 0运行,在所有情况下均为假,除非用户在贷款金额问题中键入“0”。
  • 你在每次迭代中用一个(++ CurrentLoan)递增CurrentLoan - 为什么?
  • 你有';'在for循环中的'{'之前 - 导致'{..}'的内容被认为是函数内的作用域,而不是循环的动作。这意味着它只会在for循环完成后执行,而不是在for循环的每次迭代中执行。
  • 除非用户输入负月值,否则贷款会增加而不会减少?
  • 您返回0,但您的主要功能被指定为void ..

一个工作示例(循环 - 我没有完成APR部分,因为它似乎不是你的问题):

int main(int argc, char** argv) {
    float LoanAmount;
    float Monthly; /*Prompts Number to a Float character type*/

    printf("Please enter in the Loan Amount : \n\r"); /*prompts user to enter float*/
    scanf("%f", &LoanAmount);

    printf("Please enter in the Monthly payment plan : \n\r");
    scanf("%f", &Monthly);

    printf("\nPerforming calculation using a loan of Loan Amount: %.2f \n\r", LoanAmount);
    printf("with a monthly payment of : %.0f \n\r", Monthly);

    for (; LoanAmount >= 0; LoanAmount -= Monthly) {
        printf("%.2f \n\r", LoanAmount);
    }
    return (0);
}

的变化:

  • 删除了不需要的多余变量
  • 每次迭代减少每月LoanAmount
  • 在每次迭代中打印(剩余)LoanAmount
  • for循环停止一次在零/零下

输出:

Please enter in the Loan Amount : 
11111
Please enter in the Monthly payment plan : 
1949

Performing calculation using a loan of Loan Amount: 11111.00 
with a monthly payment of : 1949 
11111.00 
9162.00 
7213.00 
5264.00 
3315.00 
1366.00