我正在try 为我的应用程序重新创建一个计算器.它看起来像是在重建一辆自行车,但这是我的第一个项目,我没想到会有这么多挑战.最后一个是浮点误差.我知道这是一个常见的问题,但我不知道如何用计算器来解决它.
显然,计算器可以很好地工作.我试着寻找一些原型,他们中的大多数都有相同的问题或比这一个更多.
为了在屏幕上显示结果,我使用了DOUBLE插值法,它给出了一个结果,例如将0.1%加到0.2%等于0.2999999.或将0.3乘以3等于0.8999999999.
四舍五入是不合适的,因为我们永远不知道小数点后有多少位有用的数字.
如何将此计算表示给用户,类似于本机计算器,例如: 我需要0.1+0.2=0.3同时1/3=0.33333333
下面是计算示例和我对字符串的插补,以显示结果:
struct air: View {
@State var data: String = "0" // creating var for showing
@State var firstNumber: Double = 0.3 // exact number which I have problem could be 0.3, 0.6
@State var secondNumber: Double = 3 // could be 3, 9, 12
@State var result: Double = 0 // result of calculation
var body: some View {
VStack{
Button("Push"){ // Initiating calculation
result = calculate(first: firstNumber, second: secondNumber)
data = String(result)
}.frame(width: 80, height: 40)
.background(Color.gray)
.foregroundColor(.white)
Text("result: Double = \(result)") // can see that result as Double is correct
.font(.title)
Text("data: String = \(data)") // can see that result as interpolated to String is incorrect and shows number with 9 in period
.font(.title)
}
}
}
func calculate(first: Double, second:Double) -> Double {
return first * second
}