【问题标题】:How to subtract a number from itself multiple times?如何多次从自身中减去一个数字?
【发布时间】:2014-02-19 03:27:40
【问题描述】:

我试图让用户输入一个数字,然后是第二个数字,它告诉程序做一些基本的数学运算多少次。我得到了工作和乘法的加法,但我不知道如何通过用户选择的次数让减法从自身减去一个数字。

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

【问题讨论】:

  • 我误解了这个问题,所以删除了我的答案。我想你误解了[v]*n,然而,v 是第一个数字,n 是第二个数字。这不是乘法。 [2]*2 => [2,2],所以减法运算会产生2-2 => 0

标签: ruby math subtraction


【解决方案1】:

怎么样:

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

【讨论】:

  • 哈!很简单!你是个天才!谢谢 Sergio,效果很好!
  • hmm,经过进一步测试,它没有正确减去,所以如果我输入第一个 2 和 2 秒,它应该返回 0,但它返回 -4,因为它乘以然后减去结果,我需要 2-2 或者说 5-5-5 = -5
  • 是的,知道了,现在我发现我的加法存在缺陷,如果我先输入 21 再输入 1 秒,它会返回 21,因为我在作弊并使用乘法。自从您回答了我的最初问题以来,我将标记为已接受。非常感谢!
  • @user3295198 恐怕这个解决方案不适用于负数,例如(-5),我已经给出了一个更好的 ruby​​ 方法来做到这一点
【解决方案2】:

这是 Ruby 方式

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

例如:

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 > 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多