• 3-23 Rspec自动化测试(开始练习)


    闰年程序

    leap_year_spec.rb
    require_relative './leap_year'
    describe "Leap Year" do 
     it "2016 is leap year" do 
     result = is_leap_year?(2016) # 把 2016 传进去  
     expect(result).to eq(true) # 检查结果应该要是 true  
     end 
     it "2017 is common year" do 
     result = is_leap_year?(2017) # 把 2017 传进去  
     expect(result).to eq(false) # 检查结果应该要是 false  
     end 
    end

    describe "text" do ... end

    it "text" do

        result = ... 

        expect(result).to eq(...)

    end 


    > book.map! do |x|
    >     x = x - 1
    >     puts x     #map!方法内部不能有输出的语法,如p, puts, print ⚠️
    > end
    1
    2
     => ❌ [nil, nil]

    有一家书店在卖哈利波特书籍系列,每一本书定价 $100 元。买两本不同的书可以打5% 的折扣、买三本不同的书可以打 10% 的折扣、买四本不同的书可以打 20%。如果买到五本可以打到 25% 的折扣。请写出一个方法可以计算价格。

    前几个测试案例会是这样:

    • 第一集买 1 本,总价应为 100 元
    • 第一集买 1 本、第二集买 1 本,总价应为 190 元
    • 第一集买 1 本、第二集买 2 本,总价应为 290 元 (要不同集数才有折扣,所以第二集第二本没有折扣)

    请继续完成。

     答案:(靠!,花了2小时。测试不难学,关键是让自己的代码通过测试。)

    #buy_book.rb 

    def book_discount(book)

      total = 0
      while book != []       # book存储未结算的书籍。
        book.delete_if{|x| x == 0 }  #删除不买的集:删除0(首次输入可能是[0,0,0,0,1])
        min_num = book.min      # 最多有5集,找出这5集中,订购的最少的那一集的本数。
        s = book.size      # 你准备买多少集?
        discount = 1      # 设定一个折扣变量
        case s
        when 1
          discount = 1
        when 2
          discount = 0.95
        when 3
          discount = 0.9
        when 4
          discount = 0.8
        when 5
          discount = 0.75
        end

        # total:结算当前获得最优的折扣的套集。 

        total += 100 * s * discount * min_num  
        # 下面两行代码目的:删除已经结算的套籍。
        book.delete_if{|x| x == min_num }
        book.map! do |x|
          x - min_num
        end
      end
      return total
    end

    ####buy_book_spec.rb

    require_relative './buy_book'   #不加.rb
    describe "Buy Book" do
      it "[2,2,2,2,2]" do
        result = book_discount([2,2,2,2,2])
        expect(result).to eq(750)
      end
      it "[1,2,3,0,0]" do
        result = book_discount([1,2,3,0,0])
        expect(result).to eq(560)
      end
      it "[2,3,1,1,1]" do
        result = book_discount([2,3,1,1,1])
        expect(result).to eq(665)
      end
      it "[10,0,0,0,1]" do
        result = book_discount([10,0,0,0,1])
        expect(result).to eq(1090)
      end
    end
  • 相关阅读:
    How to Install Linux, Apache, MySQL, PHP (LAMP) stack on CentOS 6 【Reliable】
    可以把一些常用的方法,写入js文件,引入html界面
    把功能写在方法里,函数化,方法化
    那些SQL语句
    Linux&shell之高级Shell脚本编程-创建菜单
    Linux&shell之高级Shell脚本编程-创建函数
    PHP isset()与empty()的使用区别详解
    如何打开mo文件并修改 PoEdit
    Linux&shell之如何控制脚本
    Linux&shell之显示数据
  • 原文地址:https://www.cnblogs.com/chentianwei/p/8626117.html
Copyright © 2020-2023  润新知