提问人:Monte Helm 提问时间:11/14/2023 最后编辑:HangarRashMonte Helm 更新时间:11/15/2023 访问量:49
使用 Swift 解析化学式
Parsing a chemical formula with Swift
问:
我是编码新手,一直在通过反复试验自学。我一直在开发一个应用程序来计算化合物的摩尔质量,但似乎无法让括号正常工作。例如,Mg(NO3)2 返回具有两个 Mg 原子而不是一个原子的质量。我希望这个问题对某人来说是显而易见的,因为我已经研究了好几天了。任何建议将不胜感激!
func calculateMolarMass() {
var totalMass = 0.0
var i = compoundFormula.startIndex
var massStack: [Double] = []
var operatorStack: [Character] = []
var openParenthesesCount = 0
var openSquareBracketsCount = 0
while i < compoundFormula.endIndex {
let char = compoundFormula[i]
if char.isLetter {
var elementSymbol = String(char)
i = compoundFormula.index(after: i)
while i < compoundFormula.endIndex && compoundFormula[i].isLowercase {
elementSymbol.append(compoundFormula[i])
i = compoundFormula.index(after: i)
}
var subscriptValue = ""
while i < compoundFormula.endIndex && compoundFormula[i].isNumber {
subscriptValue.append(compoundFormula[i])
i = compoundFormula.index(after: i)
}
let elementMass = atomicMasses[elementSymbol] ?? 0.0
let multiplier = Double(subscriptValue) ?? 1.0
totalMass += elementMass * multiplier
} else if char == "(" || char == "[" {
operatorStack.append(char)
i = compoundFormula.index(after: i)
if char == "(" {
openParenthesesCount += 1
} else {
openSquareBracketsCount += 1
}
} else if char == ")" || char == "]" {
let openBracket: Character = char == ")" ? "(" : "["
i = compoundFormula.index(after: i)
while !operatorStack.isEmpty && operatorStack.last != openBracket {
applyOperator(&totalMass, &massStack, operatorStack.removeLast())
}
if operatorStack.isEmpty || operatorStack.last != openBracket {
fatalError("Mismatched parentheses/brackets")
}
if char == ")" {
openParenthesesCount -= 1
} else {
openSquareBracketsCount -= 1
}
operatorStack.removeLast() // Remove the open parenthesis
if i < compoundFormula.endIndex && compoundFormula[i].isNumber {
var numberString = ""
while i < compoundFormula.endIndex && compoundFormula[i].isNumber {
numberString.append(compoundFormula[i])
i = compoundFormula.index(after: i)
}
let multiplier = Double(numberString) ?? 1.0
totalMass *= multiplier
}
}
if openParenthesesCount < 0 || openSquareBracketsCount < 0 {
fatalError("Mismatched parentheses/brackets")
}
}
while !operatorStack.isEmpty {
if operatorStack.last == "(" || operatorStack.last == "[" {
fatalError("Mismatched parentheses/brackets")
}
applyOperator(&totalMass, &massStack, operatorStack.removeLast())
}
if openParenthesesCount != 0 || openSquareBracketsCount != 0 {
fatalError("Mismatched parentheses/brackets")
}
molarMass = totalMass
} // Code for calculating Molar Mass
答: 暂无答案
评论