概述
ruby 数组相加
在Ruby中将两个数字相加 (Adding two numbers in Ruby)
Given/Input two integer numbers and we have to find the addition of the integer numbers in Ruby.
给定/输入两个整数,我们必须在Ruby中找到整数的加法。
In this problem, we will find out the way to add two integers in Ruby. Adding two numbers is not as easy as it seems because when we use gets method which stands for getting string, we get the value in the string. We will not get the appropriate result if we add those values.
在这个问题中,我们将找到在Ruby中添加两个整数的方法。 将两个数字相加并不像看起来那样容易,因为当我们使用代表获取字符串的gets方法时,我们会在字符串中获取值。 如果添加这些值,将不会获得适当的结果。
Methods used:
使用的方法:
puts: This method is used to display some message to the user.
puts :此方法用于向用户显示一些消息。
gets: This method is used to take input from the user.
gets :此方法用于接收用户的输入。
.to_i: When we take input through gets method, it is a string. For further calculations, it is mandatory to convert it into an integer for exact results and this method returns the integer conversion of the given string.
。 to_i :当我们通过gets方法获取输入时,它是一个字符串。 为了进行进一步的计算,必须将其转换为整数才能获得准确的结果,并且此方法返回给定字符串的整数转换。
+: It is a mathematical operator which accepts two numerical parameters and returns a numerical value. A binary operator to add two values.
+ :这是一个数学运算符,它接受两个数值参数并返回一个数值。 二进制运算符,用于将两个值相加。
Variables used:
使用的变量:
num1: To store the first value
num1 :存储第一个值
num2: To store the second value
num2 :存储第二个值
sum: To store the sum i.e. result
sum :存储和,即结果
Ruby代码将两个整数相加 (Ruby code to add two integer numbers)
=begin
Ruby program to add two numbers.
=end
# input the numbers and converting
# them into integer
puts "Enter first value: "
num1=gets.chomp.to_i
puts "Enter second value: "
num2=gets.chomp.to_i
# finding sum
sum=num1+num2
# printing the result
puts "The sum is #{sum}"
Output
输出量
First run:
Enter first value:
123
Enter second value:
456
The sum is 579
Second run:
Enter first value:
-120
Enter second value:
20
The sum is -100
Code explanation:
代码说明:
This program is to add two integer values and print the sum of these entered numbers. It takes two integers as input and stored them to variables, num1 and num2. Then using the + (arithmetic operator) to store the sum of these variables into the sum and stores this sum and then the puts method prints the sum value with the print statement The sum is $sum.
该程序将两个整数值相加并打印这些输入数字的总和 。 它以两个整数作为输入并将它们存储到变量num1和num2中 。 然后使用+ (算术运算符)将这些变量的总和存储到总和中并存储该总和,然后puts方法使用print语句打印总和值sum为$ sum 。
翻译自: https://www.includehelp.com/ruby/add-two-integer-numbers.aspx
ruby 数组相加
最后
以上就是落寞黑猫为你收集整理的ruby 数组相加_Ruby程序将两个整数相加的全部内容,希望文章能够帮你解决ruby 数组相加_Ruby程序将两个整数相加所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复