rounding off to the nearest number ruby - ruby

def percent_more
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
end
Now that code will tell you what percent more biggest_number is than smallest_number. But the problem is it prints out a long list of decimals, which are a pain to sort through. So if I wanted the code to only show say the first 3 numbers what would I do??

What you want to use is total_percent_more.round like so:
puts "What is the biggest number?"
biggest_number = gets.chomp
puts "What is the smallest number?"
smallest_number = gets.chomp
difference = biggest_number.to_i - smallest_number.to_i
total_percent_more = difference / smallest_number.to_f
puts "Your biggest number is #{total_percent_more.round}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
See the docs for more info :
http://www.ruby-doc.org/core-2.1.2/Float.html#method-i-round
in ruby versions earlier than 1.9 you'll need to use sprintf like so:
puts "Your biggest number is #{sprintf('%.2f', total_percent_more)}% bigger then your smallest number. Don't forget to round off to the nearest whole percent!"
You can change the amount of decimal places by changing the number.
See docs for more details:
http://www.ruby-doc.org/core-1.8.7/Kernel.html#method-i-sprintf

result = 10/6.0
puts result
printf("%.3f\n", result)
--output:--
1.66666666666667
1.667

Here is an example how to round to 2 decimal places
amount = 342
puts amount.round(2)
If you wanted to round to the nearest 3 decimal places then something like:
puts amount.round(3)

Related

Cant figure out where I am making mistake

Issue:
def average_of_three(num1, num2, num3)​
puts "Enter first number"
num1= gets.to_i
puts "Enter second number"
num2 = gets.to_i
puts "Enter third number"
num3 = gets.to_i
avg=0
avg = (num1 +num2 + num3 )/3
puts "your average is#{avg}"
end
Solution:
I was missing the following statement :
average_of_three(10, 20, 30)
This code should work if you call that method, but the method doesn't need arguments. Those variables are declared locally anyway.
Right now you'd do:
average_of_three(0, 0, 0)
Where the initial values don't matter as you ignore them anyway. They could be :zero or "Who cares!" just the same.
This isn't very Ruby code though. When writing Ruby think first in terms of data structures.
For example, to get three values:
def get_n(n = 3)
n.times.map do |i|
print "Enter number #{i+1}: "
gets.to_i
end
end
This asks a series of questions and stores the result in an array, that's what map does.
Now you can average those:
def average(values)
return unless (values.any?)
values.sum / values.length
end
This has a guard clause where it won't execute unless there's at least one value. Then it calls sum, which not surprisingly adds up all the values. Divide by the length and you're done.
So you'd tie this all together with:
values = get_n
puts "Average is: #{average(values)}"
Note: In Ruby when you divide an integer by an integer you always get an integer. This means the values get rounded. If you'd prefer to have fractional results you can switch the input converter from .to_i to .to_f. That change will cause floats to flow through the rest of the code.

Multiplying variables in Ruby?

I'm trying to create a simple pay predictor program.
I am capturing two variables, then want to multiply those variables. I have tried doing
pay = payrate * hourrate
but it seems not to work. I was told to put pay in a definition, then I tried to display the variable but it still didn't work. When I looked at the documentation, it seems that I am using the correct operator. Any guesses?
# Simple Budgeting Program
puts "What is your budget type?\nYou can say 'Monthly' 'Weekly' or 'Fortnightly'"
payperiod = gets.chomp
case payperiod
when "Monthly"
puts "You are paid monthly"
when "Weekly"
puts "You are paid weekly"
when "Fortnightly"
puts "You are paid every two weeks."
else
puts "You did not input a correct answer."
end
puts "What is your hourly rate?\n"
payrate = gets.chomp
puts "How many hours have you worked during your pay period?\n"
hourrate = gets.chomp
def pay
payrate * hourrate
end
puts "#{pay}"
preventclose = gets.chomp
The def has nothing to do with it. payrate and hourrate are strings and * means a very different thing to strings. You need to convert them to numbers first with to_i or to_f.
payrate.to_f * hourrate.to_f
You declared pay rate and hour rate as strings. In Ruby, you cannot multiply strings by other strings. However, in Ruby there are type conversions. Ruby's string class offers a method of converting strings to integers.
string = "4"
string.to_i => 4
In your case, you first need to convert BOTH strings to an integer.
def pay
payrate.to_i * hourrate.to_i
end
Here's some great information about strings.
http://www.ruby-doc.org/core-2.1.2/String.html
Hope this helps
Coercing Strings into Numbers, and Back Again
Kernel#gets generally returns a string, not an integer or floating point number. In order to perform numeric calculations, you need to coerce the string into a number first. There are a number of ways to do this, but the Kernel#Float method is often safer than String#to_i because the Kernel method will raise an exception if a string can't be coerced. For example:
print 'Pay Rate: '
rate = Float(gets.chomp)
print 'Hours Worked: '
print hours = Float(gets.chomp)
Of course, operations on floating point numbers can be inaccurate, so you might want to consider using Kernel#Rational and then converting to floating point for your output. For example, consider:
# Return a float with two decimal places as a string.
def pay rate, hours
sprintf '%.2f', Rational(rate) * Rational(hours)
end
p pay 10, 39.33
"393.30"
#=> "393.30"

I can't multiply decimals, in ruby

I'm making a interest calculator
I go 10 * .10 * 10 and i get 0 so how do i multiply a decimal without it being 0?
my source code is
def interest()
puts "Type the original loan."
loan = gets.chomp.to_i
puts "Type the amount of interest in decimal."
interest = gets.chomp.to_i
puts "How many years?"
years = gets.chomp.to_i
puts "Your interest is"
puts loan * interest * years
end
interest()
You've got integers there, so result will be an integer too. You could use 'to_f but beware, it's not good for dealing with money or anything else needing precision. Use BigDecimal instead:
require 'bigdecimal'
def interest
puts "Type the original loan."
loan = BigDecimal(gets.chomp)
puts "Type the amount of interest in decimal."
interest = BigDecimal(gets.chomp)
puts "How many years?"
years = BigDecimal(gets.chomp) # suggested in comment, agreed with that
puts "Your interest is"
puts loan * interest * years
end
What's the difference between them?
Do this
interest = gets.chomp.to_f
.to_i changes the string to an integer. An integer is a WHOLE number.
.to_f is to float, a float is a number that allows decimal places
The problem is that you're using .to_i when you don't really want to use integers here. Integers are represented without decimal parts to them, and therefore when you call .10.to_i it truncates it to 0.
Consider using floats by .to_f instead

Input string does not match a numerical range

The below ruby code is not working as expected. It doesn't seem to recognise the 1..3 range and is only reading the else condition. If I gave a number instead of a range, it works though. Not sure where I'm going wrong.
print "Enter your cost: "
cost = gets.chomp
case cost
when 1..3
puts "inexpensive"
when 3..5
puts "affordable"
else puts "no comments"
end
You're trying to match a string against an integer range. That's not going to work. Make an integer.
cost = gets.chomp.to_i
The input you get from gets is always a string, so it will never match a number range. To convert it to an integer, do this:
cost = gets.to_i
You can directly put it in case statement like so
case gets.to_i

How would I reuse a random number in ruby?

I am trying to create a random math equation (just with simple addition) where two random numbers are given to you and you need to add them up. My problem is that the two random numbers used for the answer are different from the ones that are used in the equation
puts "Choose the number range (difficulty of the equation)"
difficulty = gets.chomp
a = rand(difficulty)
b = rand(difficulty)
answer = a + b
puts "#{a} + #{b}"
UserAnswer = gets.chomp
if UserAnswer == answer
puts "good"
else
puts "bad"
end
Your problem has nothing to do with random numbers. The problem is that you are comparing a number (the sum of the random numbers) with a string (from the user input). You should replace the relevant line with:
UserAnswer = gets.to_i
By the way, I don't see any reason to use a constant here. It would most likely be better using a local variable like user_answer.
Try storing the of a and b in other two variables like a_aux and b_aux, and then refer to these instead of a and b everytime you would use a and b.

Resources