在这个程序中,我假设让用户输入数据,程序将计算他们需要的内容并显示出来。我想在这个程序中使用 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");
}
最佳答案
您可以按如下方式使用 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 循环 block 根本不执行,但 do-while 执行一次。
关于c - Do 和 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860675/