题目内容:喝汽水,一瓶汽水1元,两个空瓶子能换一瓶汽水,问n元钱能喝多少汽水?
int main()
{
int drink_count=0;//计算喝的次数
int void_bottle=0;//计算空瓶子个数
int money = 0;//计算钱的数量
//scanf("%d", &money); //输入钱的数量
while (money)//money为0则跳出循环
{
drink_count += money;
//用钱换汽水,每次都在原来基础上加上喝汽水的次数
void_bottle = money;
//花了多少钱就喝了多少瓶汽水,就得到了多少个空瓶子
//由于空瓶子直接换汽水的表达式很复杂,因为钱可等价于汽水,所以先用空瓶子换钱
money = 0;
//喝完汽水就没钱了
while (void_bottle >= 2)
//每两个空瓶子都能换一块钱
{
money++;
//换钱了
void_bottle -= 2;
//换一块钱后,空瓶子少两
}
}
//如果还有钱就继续喝汽水,没有就结束循环
printf("喝饮料次数:%d ", drink_count);
//打印喝汽水的次数
return 0;
}
想要求每增加一块钱所增加的汽水,所喝次数与钱之比可见下面代码
int main()
{
int max = 0;
int last = 0;
int money = 0;
double per = 0.0;
//scanf("%d", &money);
for (money = 0; money <= 100000; money++)
{
int tmp = money;
printf("money:%-7d ", money);
int drink_count = 0;
int void_bottle = 0;
while (money)
{
drink_count += money;
void_bottle = money;
money = 0;
while (void_bottle >= 2)
{
money++;
void_bottle -= 2;
}
}
money = tmp;
per = (double)drink_count / money;
//新手亮点:由于左右两边都是整型无法得到浮点数,所以需要强制类型转化
printf("喝饮料次数:%-5d ", drink_count);
printf("增加一块钱多喝几瓶:%-4d ",drink_count - last);
printf("喝次与钱之比:%.3lf\n", per);
int new = drink_count - last;
if (money > 0)
{
if (new > max)
{
max = new;
}
}
last = drink_count;
}
printf("max=%d\n", max);
return 0;
}