Help us understand the problem. What is going on with this article?

【Kotlin】基本問題

Kotlinで基本問題

Kotlinでandroidアプリを作りたいと思い、
基本文法の勉強し始めました。勉強しながら、メモしていきんす。

FizzBuzz

変数宣言, for, ifなど

fun main(){
    var fiz_num: Int=3
    var buz_num: Int=5
    var n: Int=100
    var message: String = ""

    for (i in 1..n){
        if (i%fiz_num==0 && i% buz_num==0){
            message="$i:FizzBuzz"
        }else if(i%fiz_num==0){
            message="$i:Fizz"
        }else if(i%buz_num==0){
            message="$i:Buzz"
        }else{
            message="$i"
        }
        println("$message")
    }
}

下のように記述するこことで、ifの返り値を分岐させることもできる。おしゃれ。

fun main(){
    var fiz_num: Int=3
    var buz_num: Int=5
    var n: Int=100
    var message: String = ""

    for (i in 1..n){
        message=if (i%fiz_num==0 && i% buz_num==0){
            "$i:FizzBuzz"
        }else if(i%fiz_num==0){
            "$i:Fizz"
        }else if(i%buz_num==0){
            "$i:Buzz"
        }else{
            "$i"
        }
        println("$message")
    }
}

  
whenとかいう分岐も使ってみた。
なんかおしゃれなので、無理にでも使っていきたい。

fun main(){
    var message: String=""

    for (i in 1..100){
        message=when{
            i%3==0 && i%5==0 -> "$i:FizzBuzz"
            i%3==0 -> "$i:Fizz"
            i%5==0 -> "$i:Buzz"
            else -> "$i"
        }
        println(message)
    }
}

フィボナッチ数列

関数の作り方など

fun main(){
    var n: Int=20
    for (i in 1..n){
        println(fibo(i))
    }

}

fun fibo(num: Int):Int{
    if (num==0){
        return 1
    }else if (num==1){
        return 1
    }else{
        return fibo(num-1)+fibo(num-2)
    }
}

whenを関数の返り値として使うとこんな感じ。

fun main(){
    var n: Int=20
    for (i in 1..n){
        println(fibo(i))
    }

}

fun fibo(num: Int):Int{
    return when{
        num==0 -> 1
        num==1 -> 1
        else -> fibo(num-1)+fibo(num-2)
    }
}
tnaga77
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした