gpt4 book ai didi

swift - 如何在 Swift 中获取范围的值

转载 作者:行者123 更新时间:2023-11-30 10:16:30 28 4
gpt4 key购买 nike

我用 swift 编写了以下函数:

func FFT_Analyzer (frequencies:[Double], magnitudes:[Double], sort_mag:[Double], harmonics:[Double]) -> (chatter_freq:Double,
chatter_mag:Double) {


//establish a counter to iterate through all the arrays:
var ffcounter = 0
var temp_Bool = 0
var chatter_freq:Double = 0
var chatter_mag:Double = 0

//establish a while loop that runs for the entirety of the frequency/FFT arrays:
while ffcounter < frequencies.count {

//use y_descend, to go down the frequencies with descending magnitude
var chatter_mag:Double = sort_mag[ffcounter]
println("The chatter magnitude is: \(chatter_mag)")

//determine the index of the frequency with highest amplitude
var mag_index = find(magnitudes, chatter_mag)
println("The chatter inded is: \(mag_index)")

//using the index, find the corresponding frequency:
var chatter_freq:Double = frequencies[mag_index!]
println("The chatter frequency is: \(chatter_freq)")

//use a FOR loop to check whether this frequency is a forced frequency/harmonic:
for element in harmonics {
if (((element-1) < chatter_freq) && (chatter_freq < (element+1))) {
temp_Bool = 0
break
}

else{
temp_Bool = 1
continue
}
}
if temp_Bool == 0 {
ffcounter = ffcounter + 1
continue
}
else {
println(chatter_freq)
println(chatter_mag)
break
}

//return (chatter_freq, chatter_mag)
}
println(ffcounter)
println(temp_Bool)
println(chatter_freq)
println(chatter_mag)

return (chatter_freq, chatter_mag)
}

为了使变量在作用域内,我在 while 和 for 循环之前定义了 ffcounter、temp_Bool、chatter_freq 和 chatter_mag。但是我遇到了以下问题:

当我的代码运行完成时,ffcounter 和 temp_Bool 将更新为其最终值(分别为 2 和 1),但是,chatter_freq 和 chatter_mag 的值不会传递到函数末尾。换句话说,chatter_freq 和 chatter_mag 是 while 循环内的更新,但我无法将这些值传递到 while 循环之外。结果chatter_freq 和chatter_mag 等于它们的初始值:0.0。

有谁知道如何将值移出更新代码块的“范围”?

最佳答案

您正在循环内声明这两个变量的实例,即使您之前已在循环外声明了它们。

只需将循环内的内容更改为:

var chatter_mag:Double = sort_mag[ffcounter]
var chatter_freq:Double = frequencies[mag_index!]

至:

chatter_mag = sort_mag[ffcounter]
chatter_freq = frequencies[mag_index!]

关于swift - 如何在 Swift 中获取范围的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688806/

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