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 3 years have passed since last update.

Rubyで1~100を各々4乗して足すプログラムを書いてみた

Last updated at Posted at 2021-07-04

1の4乗+2の4乗 ... 100の4乗 の合計を出力するプログラムを書きたい。

  def calculate
    # 1の4乗 + 2の4乗+ ・・・ 100の4乗の合計を出力
    num = 1
    sum = 0
    while num <= 100
      sum = num**4 + sum
      num += 1
    end
    puts sum
  end

1**4は1の4乗の計算式らしい

処理の流れ

一回目の処理

sum = num**4 + sumは
sum = 1の四乗 + 0
となる。
ruby では右辺が左辺に代入されるので、
1がsumに代入される。
num += 1

num = num + 1の省略記法

1の四乗から2の四乗にしていく。

二回目の処理

sum = 2**4+ 1となる
sum = 17となる。
num += 1は
2の四乗から3の四乗にしたいのでこう書いてる。

while num <= 100
こう書いてる通り、この処理を100まで続ける

1の4乗+2の4乗 ... 100の4乗 の和を求める数学の計算式は分かりませんが、プログラミング言語初心者の自分でも、
1の4乗+2の4乗 ... 100の4乗 の和を求めるプログラムは書けるのです。
プログラミング面白いなって思いました。

0
0
2

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?