gpt4 book ai didi

ios - Swift - 二次方程求解器给出错误的结果?

转载 作者:行者123 更新时间:2023-11-29 00:52:41 24 4
gpt4 key购买 nike

我是 swift 的新手,我正在尝试制作一个简单的应用程序来求解方程式(线性或二次方程式)。用户必须输入 a、b、c 的值(方程为:ax^2 + bx + c = 0),如果 a = 0,应用程序求解线性方程,如果 a != 0,应用程序求解二次方程(或告诉它无解)。

问题是.. 线性方程部分工作得很好并且给出了正确的结果,但是该应用程序给出了二次方程的错误结果!例如,如果 a = 4,b = 12,c = 8,结果应该是 x1 = - 1,x2 = -2,但我在应用程序中得到的解决方案是 x1 = -16.0,x2 = -32.0

x1/x2 似乎是对的(0.5)但结果完全错误

这是我写的代码

import UIKit
import Foundation

class ViewController: UIViewController {

@IBOutlet weak var EnterA: UITextField!
@IBOutlet weak var EnterB: UITextField!
@IBOutlet weak var EnterC: UITextField!
@IBOutlet weak var LabelYourEquation: UILabel! // gonna deal with this later
@IBOutlet weak var Button: UIButton!
@IBOutlet weak var LabelX1: UILabel!
@IBOutlet weak var LabelX2: UILabel!


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

Hide()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


var a = Double()
var b = Double()
var c = Double()
var delta = Double()
var x1 = Double()
var x2 = Double()
var linearEquation = Bool()
var quadraticEquation = Bool()

func checkEquation() {
if a == 0 {
linearEquation = true
quadraticEquation = false
} else if a != 0 {
quadraticEquation = true
linearEquation = false
}
}



func linearEquationResolution() -> Double {
x1 = -c / b
LabelX2.hidden = true
LabelX1.text = "x = \(x1)"
return x1
}


func Delta() -> Double {
delta = (b * b) - (4 * a * c)
return delta
}

func quadraticEquationResolution() {
if delta >= 0 {
x1 = ( -b + sqrt(delta)) / 2*a
x2 = ( -b - sqrt(delta)) / 2*a
LabelX1.hidden = false
LabelX2.hidden = false
LabelX1.text = "x1 = \(x1)"
LabelX2.text = "x2 = \(x2)"

} else if delta < 0 {
LabelX1.text = "The equation has no solution"
LabelX2.hidden = true

}
}


func solveIt() {
if linearEquation == true {
linearEquationResolution()
} else if quadraticEquation == true {
Delta()
quadraticEquationResolution()
}
}


func Hide() {
LabelX2.hidden = true
LabelX1.hidden = true
}





@IBAction func SolveItAction(sender: AnyObject) {

a = Double(EnterA.text!)!
b = Double(EnterB.text!)!
c = Double(EnterC.text!)!
checkEquation()
solveIt()

}




}

有什么想法吗?我做错了什么?

最佳答案

你错误地乘以 a 而不是除以

( -b + sqrt(delta)) / (2*a)

关于ios - Swift - 二次方程求解器给出错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37944561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com