Ruby - Print Power of a Number

1. Introduction

The power (or exponentiation) of a number represents the number of times a number is multiplied by itself. In Ruby, we can calculate the power of a number using the ** operator. In this tutorial, we'll create a simple program to take two numbers from the user: the base and the exponent, and then calculate and display the result.

2. Program Steps

1. Set up the Ruby development environment.

2. Prompt the user to input the base and exponent numbers.

3. Calculate the power using the ** operator.

4. Display the result to the user.

3. Code Program

# Prompt the user for a base number
puts "Enter the base number:"
base = gets.chomp.to_f
# Prompt the user for an exponent
puts "Enter the exponent:"
exponent = gets.chomp.to_f
# Calculate the power of the number
result = base ** exponent
# Display the result
puts "#{base} raised to the power of #{exponent} is: #{result}"

Output:

Enter the base number:
2
Enter the exponent:
3
2.0 raised to the power of 3.0 is: 8.0

Explanation:

1. gets: Captures user input, which is read as a string by default.

2. chomp: Removes the newline character, which gets added when the user presses Enter.

3. to_f: Converts the string input to a floating-point number to handle decimal points in the calculation.

4. : This is the exponentiation operator in Ruby, which calculates the power of a number.

5. The program first captures the base and exponent from the user and then calculates the result using the operator. Finally, it displays the result back to the user.

By following these steps, we can easily calculate and display the power of any given number in Ruby.


Comments