所以我首先写下我是这个网站的新手(今天),以及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
答案 0 :(得分:2)
好的问题是您选择的数据结构,根据定义,哈希必须始终维护一组唯一键以映射到其值。现在你可以尝试使用散列设置的东西是将所有键映射到空数组,然后将数值添加到其中,然后对其各自的数组中的每个值处理该操作(因为你忽略了任何操作的顺序)
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]}