Вопрос

I am trying to get user input for a number then a second number that tells the program how many times to do some basic math. I got the addition to work and the multiplication, but I am not sure how to get the subtraction to subtract a number from itself by the user selected number of times.

print "Please Enter a numeric value: ";  # get the first input from user

input1 = STDIN.gets.chomp!.to_i

puts ("\n" * 2)                           #Scroll the screen 3 times

print "Enter total number of times a value needs to be computed from #{input1} "; 

input2 = STDIN.gets.chomp!.to_i

puts ("\n" * 2) 

print "Addition : ", (input1.to_i * input2.to_i), "\n";       
print "Subtraction : " , (input1.to_i - input2.to_i), "\n";     
print "Multiplication : " , (input1.to_i ** input2.to_i), "\n";
Это было полезно?

Решение

How about:

print "Subtraction : " , input1.to_i-(input1.to_i*input2.to_i), "\n"; 

Другие советы

Here's the Ruby way

print "Subtraction : " , Array.new(input2,input1).inject(:-), "\n";

Ex:

1.9.3p448 :058 > Array.new(3,-5)
 => [-5, -5, -5] 
1.9.3p448 :059 > Array.new(3,-5).inject(:-)
 => 5 
1.9.3p448 :060 > 
1.9.3p448 :061 >   Array.new(3,5)
 => [5, 5, 5] 
1.9.3p448 :062 > Array.new(3,5).inject(:+)
 => 15 
1.9.3p448 :063 > 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top