打印 1 ~ 4 之内三位数的值,且每个值内数字不能重复:
这道题的重点是:for ( ) 循环的运用 和 a != b && b != c && c != a 。
void Total()
{
int a = 0;
int b = 0;
int c = 0;
int count = 0;
for (c = 1; c <= 4; c++)
{
for (b = 1; b <= 4; b++)
{
for (a = 1; a <= 4; a++)
{
if (a != b && b != c && c != a)
{
int total = c * 100 + b * 10 + a;
printf("Total = %d ", total);
count++;
}
}
}
}
printf("\ncount = %d\n", count);
}
int main()
{
Total();
return 0;
}
求每个阶段可获得的奖金:
这道题主要考察分支语句的运用,可以用 if ( ) 语句或 switch 语句,这里的逻辑很简单,就是将每个阶段可提成的的比例分开,然后用 if ( ) 语句 或 switch 语句 将他们连接起来。
int main()
{
int profit = 0;
int bonus = 0;
scanf("%d", &profit);
//利润低于或等于10万时,奖金可提成10%
if (profit <= 100000)
{
bonus = profit * 0.1;
}
//当利润高于10万,低于20万时,低于10万的部分按10%提成,高于10万的部分,可提成7.5%
else if (profit <= 200000)
{
bonus = 100000 * 0.1 + (profit - 100000) * 0.075;
}
//20万到40万之间时,高于20万的部分可提成5%
else if (profit <= 400000)
{
bonus = 100000 * 0.1 + 100000 * 0.075 + (profit - 200000) * 0.05;
}
//40万到60万之间时,高于40万的部分,可提成3%
else if (profit <= 600000)
{
bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + (profit - 400000) * 0.03;
}
//高于60万时,超过超过60万的部分,可提成1.5%
else
{
bonus = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + (profit - 600000) * 0.015;
}
printf("%d ", bonus);
return 0;
}
上面的代码有很多重复出现常量的地方,重复的常量可以将他们赋值给一个变量,用这个变量去代替常量出现,这样虽然不会减少计算机的计算量,但是优化了代码,既让代码更好看了,又可以更好的更改代码。
优化后:
int main()
{
int profit = 0;
int bonus = 0;
int bonus1 = 100000 * 0.1;
int bonus2 = bonus1 + 100000 * 0.075;
int bonus3 = bonus2 + 200000 * 0.05;
int bonus4 = bonus3 + 200000 * 0.03;
scanf("%d", &profit);
//利润低于或等于10万时,奖金可提成10%
if (profit <= 100000)
{
bonus = profit * 0.1;
}
//当利润高于10万,低于20万时,低于10万的部分按10%提成,高于10万的部分,可提成7.5%
else if (profit <= 200000)
{
bonus = bonus1 + (profit - 100000) * 0.075;
}
//20万到40万之间时,高于20万的部分可提成5%
else if (profit <= 400000)
{
bonus = bonus2 +(profit - 200000) * 0.05;
}
//40万到60万之间时,高于40万的部分,可提成3%
else if (profit <= 600000)
{
bonus = bonus3 + (profit - 400000) * 0.03;
}
//高于60万时,超过超过60万的部分,可提成1.5%
else
{
bonus = bonus4 + (profit - 600000) * 0.015;
}
printf("%d ", bonus);
return 0;
}
至此,今日学习就结束了