0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

フィボナッチ数列

Last updated at Posted at 2018-11-26

C言語でフィボナッチ数列の和を計算

fibo.c
# include <stdio.h> // 標準入出力

// メイン関数
int main(void) {
  int n; // 入力用
  unsigned long x1=0, x2=1, x3; // フィボナッチ計算用
  // 入力
  printf("正の整数を入力してください : ");
  scanf("%d", &n);

  // 0以下のときは弾く
  if(n < 0) {
    printf("不正な値が入力されました.\n");
    return 1;
  }
  // f(0) = 0
  else if(n == 0) {
    printf("0\n");
  }
  // f(1) = 1
  else if(n == 1) {
    printf("1\n");
  }
  // f(n) = f(n-1) + f(n-2)
  else {
    n = n-1; // 繰り返しの回数を調整
    while(n > 0) {
      x3 = x1 + x2;
      x1 = x2;
      x2 = x3;

      n--;
    }
    printf("%lu\n", x1);
  }



  return 0;
}

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?