c语言智力题

每瓶汽水1元,两个空瓶可以置换一瓶汽水,现在有20元,最多能喝多少
瓶汽水?
分析:
首先,有20元,所以可以喝20瓶水(total = 20),有20个空瓶子。

  20/2------------10(水)(total += 20)
  bottles = 20/2 +20%2-------------(bottles = 10)
  10/2---------------5(水)---------(total += 5)
  bottles = 10/2 + 10%2----------- (bottles = 5)
  5/2-----------------2(水)-----------(total += 2)
  bottles = 5/2 +5%2---------------  (bottles = 3)
  3/2-----------------1(水)--------(total += 1)
  bottles = 3/2 +3%2----------------(bottles = 2)
  2/2------------------1(水)--------(total += 1)
  bottles -------------------------------1

以上用的是数学的算法,下面编程实现:

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

int main()
{
    int total = 20;//初始条件-----20元----20瓶水
    int bottles = 20;//20个空瓶子
    while (bottles > 1)//当还有2个及以上的瓶子时,执行循环
    {
        total += bottles/2;
        bottles = bottles/2 + bottles % 2;
    }
    printf("total = %d\nbottles = %d\n",total,bottles);
    system("pause");
    return 0;
}

这里写图片描述

但是,这道题如果放在实际生活中,或许可以得到40瓶水,因为如果
当只剩一瓶水时,你可以向店家借一瓶水,使之和你手中的空瓶构成
2个空瓶,这时你还可以换一瓶水,当喝完水后再把这个空瓶子还给
店家,是不是很机智呢,哈哈,如果你还有更好的方法,欢迎指教哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值