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.

Ruby計算 気を付けるべきポイント(変数の入力)

Posted at

Rubyにて変数に文字列代入の際のポイント

今回行いたいのは、Rubyにて数値の計算。
(例) 入力した数値の倍の値を表示するプログラム。(2→4)

1.まず入力を考える。

変数に数を代入する。
代入は、入力によって行う。
入力の際は、getコマンドを用いる

nunber=gets

これで入力を行えば、代入される。

2.計算を考える。

今回は倍にするという単純な計算。
*が×を表す。

number2=number*2

3.結果表示

計算結果はnumber2に入ってるので、

print number2

とすると、結果は.....

2
2

あれ??

文字列として、代入されてたことが発覚
.to_iをつけて、文字列→数値にする必要あり

number = gets.to_i
number2=number*2
print number2

これで表示は

4

となった。

4.参考ブログ

0
0
0

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?