【问题标题】:Do and While LoopDo 和 While 循环
【发布时间】:2015-07-03 20:04:10
【问题描述】:

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

  • 到目前为止,我已经成功地使用了 For 循环,但是我在如何为这个程序使用 While 和 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");

}

【问题讨论】:

  • 你是在找人帮你做作业吗?
  • @jeff 我在征求意见.......
  • 顺便说一句,While and Do loop 是什么?

标签: c loops for-loop while-loop


【解决方案1】:

您可以按如下方式使用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 执行一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 2011-04-07
    • 2018-05-09
    • 1970-01-01
    • 2016-02-21
    • 2016-02-04
    • 2020-11-26
    • 2015-02-16
    相关资源
    最近更新 更多