如何多次从自身中减去一个数字?

时间:2022-02-05 13:42:35

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";

2 个解决方案

#1


0  

How about:

怎么样:

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

#2


0  

Here's the Ruby way

这是Ruby方式

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 > 

#1


0  

How about:

怎么样:

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

#2


0  

Here's the Ruby way

这是Ruby方式

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 >