C#基础编程1

有个小学生的数学题目,啤酒2元钱一瓶,4个瓶盖换1瓶,2个空瓶子换1瓶。现利用程序来计算。每个金额可购买的多少啤酒。(不允许从别处借瓶盖和瓶子)
定义方法:int CanBuy(int money)
在主方法调用它,由用户输入金额,对返回的啤酒数量用Debug.Assert()进行判定,假如输入10元钱,可判定输出是15瓶。
在控制台窗口输出啤酒数量,在“输出”窗口利用Debug.WriteLine()打印计算过程,比如:
“10元钱买了5瓶啤酒
喝完后留下5个瓶盖和5个瓶子
5个瓶盖换了1瓶啤酒,余下1个瓶盖
5个瓶子换了2瓶啤酒,余下1个瓶子
……
喝完后留下3个瓶盖和1个瓶子”
代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            string money = Console.ReadLine();
            int num = CanBuy(Convert.ToInt32(money));
           // Debug.Assert();
            Console.WriteLine(num);
        }

        static int CanBuy(int money)
        {
            // 计算买多少瓶
            int n = money / 2;
            Debug.WriteLine($"{money}元买了{n}瓶啤酒");
            int cap = n;
            int bottle = n;
            int sum = n;
            
            while (bottle >= 2||cap>=4)
            {
                Debug.WriteLine($"喝完后留下{cap}个瓶盖和{bottle}个瓶子");
                int s = bottle / 2;
                int x = bottle % 2;
                int t = cap / 4;
                int y = cap % 4;
                Debug.WriteLine($"{cap}个瓶盖换了{t}瓶啤酒,余下{y}个瓶盖");
                Debug.WriteLine($"{bottle}个瓶子换了{s}瓶啤酒,余下{x}个瓶子");
                sum += (s + t);
                bottle = x + s + t;
                cap = y + s + t;
            }
            Debug.WriteLine($"喝完后留下{cap}个瓶盖和{bottle}个瓶子");
            return sum;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值