C编程:for循环 - 计算员工的资金支出

时间:2015-09-22 09:01:09

标签: loops for-loop

    #include <stdio.h>
    main()
    {
    int i;
    int Employees;
    int PricePerEmployee = 30;
    int total = 0;
    printf("How many employees?\n");
    scanf(" %d", &Employees);
    for (i=1; i<=Employees; i++)
    {
        total += Employees * PricePerEmployee;
    }
    printf("total: %d", total);
    return 0;    }

我们说我有2名员工。它打印120而不是60。 现在,当我尝试将i = Employees放在for循环中时,我得到了完美的结果。 我很困惑。 i = 1,不代表&#34;我从第一个员工开始?&#34;。

1 个答案:

答案 0 :(得分:0)

如果您只想在员工上花费很多,那么您不需要使用for-loop,您可以通过以下方式实现此目的

#include <stdio.h>
main()
{
int i;
int Employees;
int PricePerEmployee = 30;
int total = 0;
printf("How many employees?\n");
scanf(" %d", &Employees);
total = Employees * PricePerEmployee;
printf("total: %d", total);
return 0;    
}

如果你想使用for-loop,那么@avinash在评论中建议如何:

#include <stdio.h>
main()
{
int i;
int Employees;
int PricePerEmployee = 30;
int total = 0;
printf("How many employees?\n");
scanf(" %d", &Employees);
for (i=1; i<=Employees; i++)
{
     total += PricePerEmployee;
}
printf("total: %d", total);
return 0;    
}

您的代码无法按预期运行,因为:

total += Employees * PricePerEmployee;

表示

total = total + (Employees * PricePerEmployee);

因为Employees * PricePerEmployee是预期的输出,你把它放在循环中。让Employees = 2PricePerEmployee = 30然后你的循环就像这样:

1st run :
total = total + (Employees * PricePerEmployee);
total = 0 + (2 * 30) = 60;
2nd run :
total = total + (Employees * PricePerEmployee);
total = 60 + (2 * 30) = 120;