Do 和 While 循环

Do and While Loop

在这个程序中,我假设让用户输入数据,程序会计算出他们需要什么并显示出来。我想为这个程序使用 while、for 和 do 循环。

这是我的代码:

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

float load()
{
    float sal = 0.0;    
    printf("Enter Salary\n");
    scanf("%f", &sal);
    return sal;
}

float calcRate(float s)
{
    if (s > 40000)
        return 4.0;
    if (s >= 30000 && s <= 40000)
        return 5.5;
    if (s < 30000)
        return 7.0;

}
void calcRaise(float sal, float rate, float *raise, float *totraise)
{
    *raise = (sal*rate) / (float)100;
    *totraise = *totraise + *raise;

}
void calcNewSal(float sal, float raise, float *newsal, float *totnewsal)
{
    *newsal = sal + raise;
    *totnewsal = *totnewsal + *newsal;

}
void calcTotSal(float *sal, float *totsal)
{
    *totsal = *totsal + *sal;
}

void print(float sal, float rate, float raise, float newsal, float totnewsal, float totraise, float totsal)
{

    printf("     %0.2f  %0.2f  %0.2f  %0.2f\n", sal,rate,raise,newsal);


}

void main()
{
    float sal = 0.0;
    float rate, raise, newsal;
    float totraise = 0;
    float totnewsal = 0;
    float totsal = 0;
    printf("     Salary  Rate %%  Raise  New Salary\n");


        for (int i=1;i<=7;i++)
        {
        sal = load();
        rate = calcRate(sal);
        calcRaise(sal, rate, &raise, &totraise);
        calcNewSal(sal, raise, &newsal, &totnewsal);
        calcTotSal(&sal, &totsal);

        print(sal, rate, raise, newsal, totsal, totraise, totnewsal);
        fflush(stdin);

        }
    printf("Total: %0.2f %0.2f %0.2f  \n", totsal, totraise, totnewsal);
    system("pause");

}

您可以按如下方式使用 while 循环:

int i=1;
while(i<=7)  {
    sal = load();
        rate = calcRate(sal);
        calcRaise(sal, rate, &raise, &totraise);
        calcNewSal(sal, raise, &newsal, &totnewsal);
        calcTotSal(&sal, &totsal);

        print(sal, rate, raise, newsal, totsal, totraise, totnewsal);
        fflush(stdin);
        i++;
}

而 do-while 如下:

int i=1;
do  {
        sal = load();
        rate = calcRate(sal);
        calcRaise(sal, rate, &raise, &totraise);
        calcNewSal(sal, raise, &newsal, &totnewsal);
        calcTotSal(&sal, &totsal);

        print(sal, rate, raise, newsal, totsal, totraise, totnewsal);
        fflush(stdin);
        i++;
} while(i<=7);

以上两者都与您编写的 for 循环具有相同的效果。迭代次数在这里是硬编码的,所以 while 和 do-while 之间不应该有任何明显的区别。但是,如果将 i 初始化为 8 而不是 1,您会注意到 while 循环块根本不执行,但 do-while 执行一次。