【问题标题】:Ruby calculator - hash not storing correctlyRuby 计算器 - 哈希未正确存储
【发布时间】:2017-02-28 05:04:07
【问题描述】:

所以我将首先写下我是这个网站的新手(今天)以及 Ruby 编程语言(3 天前),所以不要害怕撕开我的代码——我我正在努力学习并变得更好。

基本上.. 我正在创建一个控制台计算器,它能够从用户那里读取一个简单的数学问题(或一连串数学问题)并求解方程。它不使用操作顺序或任何花哨的东西(还),它基本上可以工作,除了这个我无法弄清楚的奇怪错误。

Userinput = "1 + 2 + 3 - 4"
# First I split the user input into an array of stirngs and then loop over the
# array of strings and depict whether a string is a key or hash (see code below)

# program should store these characters in a hash like so.. 
hash = { nil=>1, "+"=>2, "+"=>3, "-"=>4 }

然后我会使用哈希的键来确定我接下来是加、减、乘还是除。

一切正常!只是当我遇到超过 2 个操作(即 1 + 2 - 0 + 3)的问题时,程序会随机遗漏一些键和运算符。我一直在尝试不同的示例来搜索模式,但找不到源。下面我将发布问题的示例及其输出,以及哈希本身,然后是完整的源代码。提前感谢您的任何帮助或批评!

示例格式

程序输入(用户提示,用户输入)-- 程序输出(方程之和)—— 执行结束时的哈希

示例 1

输入一个数学问题(例如 40 / 5):40 / 5 + 2 - 5 * 5 - 5 * 5 - 100

-450

{nil=>40, "/"=>5, "+"=>2, "-"=>100, "*"=>5}

示例 2

输入一个数学问题(例如 40 / 5):1 + 2 - 0 + 3

4

{nil=>1, "+"=>3, "-"=>0}

示例 3

输入一个数学问题(例如 40 / 5):10 - 5 * 2 + 8 + 2

12

{nil=>10, "-"=>5, "*"=>2, "+"=>2}

源码:main.rb

=begin
  
  main.rb
  Version 1.0
  Written by Alex Hail - 10/16/2016
 
  Parses a basic, user-entered arithmetic equation and solves it
 
=end

@operationsParser = ""    # global parser
@lastKeyAdded = ""

private
def appointType(sv)
    if sv =~ /\d/
      sv.to_i
    else
      sv
    end
end

private
def operate(operations)
  sum = 0
  operations.each do |k, v|
    if k.nil?
      sum += v
    else
      case k
        when '+' then sum += v
        when '-' then sum -= v
        when '*' then sum = sum * v  
        when '/' then sum = sum / v
        else
      end
     end
   end
   sum
 end

private
def solveEquation
  print "Type a math problem (ex. 40 / 5): "
  userInput = gets.chomp
  
  #array to hold all numbers and their cooresponding operation
  operations = {}   # <== Empty hash
  
  #split the user input via spaces
  @operationsParser = userInput.split(" ")
  
  #convert numbers into numbers store operators in hash ( nil => 40, "/" => 5) -- would be 40 / 5
  @operationsParser.each do |stringValue|
    if appointType(stringValue).is_a? Integer
      

     operations[@lastKeyAdded != "" ? @lastKeyAdded : nil] = appointType(stringValue)
        
    else #appointType will return a string by default
      keyToAdd = appointType(stringValue)
      @lastKeyAdded = keyToAdd
    end
  end
  
  #check if operators(+, *, -, /, or nil) in the keys are valid, if not, error and exit, if so, operate
  operations.each do |k,v|
    case k
      when '+'
      when '-'
      when '*'    
      when '/'
      when nil
      else
        # Exit the program if we have an invalid operator in the hash
        puts "Exiting program with error - Invalid operator used (Only +, -, *, / please)"
        return
    end
  end
  
  sum = operate(operations)
  
  
  puts sum, operations
end

solveEquation

【问题讨论】:

  • 你不能拥有{ "+" =&gt; 1, "+" =&gt; 2 },这是不可能的。请记住,每个键的哈希值仅限于一个实例,因此如果一个令牌出现两次,这将崩溃。数组呢?
  • 哦,你说的很对!愚蠢的我..我可能只使用一个数组并以这种方式解析它。谢谢!!
  • 您可以将您的序列转换为数组中的Polish notation,例如:2+3*4-1 变为['-', ['+', 2, ['*', 3, 4]], 1]
  • tadman 从我嘴里说出了这句话,这是本科时的 Java 作业。亚历克斯你也在寻找解析答案吗?
  • 今晚下班后我会研究一下波兰符号。我会在相当长的一段时间内更新这个计算器,所以我会有足够的时间来重构。谢谢大家!

标签: ruby hash calculator


【解决方案1】:

好的,问题在于您选择的数据结构,根据定义,哈希必须始终维护一组唯一键以映射到其值。现在,如果您对使用哈希死心塌地,您可以尝试将所有键映射到空数组,然后向其中添加数值,然后对相应数组中的每个值处理该操作(因为您以任何方式忽略操作顺序)

h = Hash.new([]) #to set the default value of each key to an empty arrary

那么当你处理你的数组时,它应该是这样的

{nil =>[1], '+' => [1, 2, 3], '-' => [3, 7], '*' => [4, 47], '/' => [3, 5]}

【讨论】:

  • 有人在我原来的帖子的 cmets 中回答了我的问题,但这也很有帮助,所以我将把这个作为公认的答案,让人们知道我的问题已经解决。
  • 好吧,祝你在追求知识的过程中好运。
猜你喜欢
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 2016-06-23
  • 2018-01-25
  • 2022-01-25
  • 2012-07-28
  • 2022-10-01
  • 1970-01-01
相关资源
最近更新 更多