Hello , Ruby!

Question

Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Answer

程序中主要使用了

  • for i in start .. end循環(huán)結(jié)構(gòu),也可以用 times,while實現(xiàn)
  • if then else 選擇結(jié)構(gòu)
  • % 求余運算
  • and 與邏輯運算
  • 數(shù)組<<運算符 :數(shù)組元素追加,ruby的數(shù)組比較靈活,聲明時可以不申明大小。
  • 方法定義:def function_name(args,...) ... end
# @param {Integer} n
# @return {String[]}
def fizz_buzz(n)
    result = Array.new()
    for i in 1 .. n
        if i % 3 == 0 and i % 5==0 then
          result << "FizzBuzz"
        else 
            if i % 3 == 0 then
              result << "Fizz"
            else 
                if i % 5 == 0 then
                result << "Buzz"
                else
                result << "#{i}"
                end
            end
         end
    end
    return result
end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容