尽管不再满足循环条件,但仍卡在While循环中

时间:2020-02-03 07:20:30

标签: ios swift while-loop infinite-loop

我对使用Swift进行编码非常陌生,现在我正试图编写一个程序,该程序只需要预算和一些餐厅,然后尝试根据剩余预算确定您要吃的东西。似乎我的代码应该可以正常工作,但是由于某种原因,只要在经过一定数量的迭代后进入while循环,当totalPrice不再大于预算时,它就无法识别。如果我在while循环的末尾放置一个if条件,验证totalPrice是否大于预算,它将识别出它不是,然后执行我放在花括号中的内容,但不会离开while循环。我真的对发生的问题感到困惑,并且非常感谢能帮助您理解我的代码本身存在的问题。非常感谢您的帮助!

import UIKit

var prices = [30,10.99,10.5,11.7,13.99,7.99,8.99,0]
var tips = [0.20,0.18,0.18,0.18,0.18,0.15,0.15,0.0]
var restaurants = ["Salty Snow","Kerby Lane","Milto's","Trudy's","Madam Mam's","Vert's","Teji's","Home"]
var daysOfWeek = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"]
let taxRate = 0.0825
var budget = 50.0

for i in 1...14{
    print("Week \(i)")
    for day in daysOfWeek {
        var randInt = Int.random(in:0..<8)
        var totalPrice = prices[randInt]+(prices[randInt]*taxRate)+(prices[randInt]*tips[randInt])
        while totalPrice > budget {
            var randInt = Int.random(in:0..<8)
            var totalPrice = prices[randInt]+(prices[randInt]*taxRate)+(prices[randInt]*tips[randInt])
        }
        print(totalPrice, randInt, budget)
        var place = restaurants[randInt]
        budget = budget - totalPrice
        print("\(day) meal: \(place), budget now \(budget)")

    }
    print()
    budget += 50
}

2 个答案:

答案 0 :(得分:0)

在while循环中从totalPrice变量中删除var,因为它每次都不会更改,而是每次都创建新变量

 while totalPrice > budget {
    var randInt = Int.random(in:0..<8)
        totalPrice = prices[randInt]+(prices[randInt]*taxRate)+(prices[randInt]*tips[randInt])
  //var totalPrice = prices[randInt]+(prices[randInt]*taxRate)+(prices[randInt]*tips[randInt])
     }

答案 1 :(得分:0)

在while循环中添加var totalPrice而不是更新totalPrice时,您定义了一个具有相同名称的新变量,这就是为什么条件从未匹配且变成无限循环的原因。使用这个:

var prices = [30,10.99,10.5,11.7,13.99,7.99,8.99,0]
var tips = [0.20,0.18,0.18,0.18,0.18,0.15,0.15,0.0]
var restaurants = ["Salty Snow","Kerby Lane","Milto's","Trudy's","Madam Mam's","Vert's","Teji's","Home"]
var daysOfWeek = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"]
let taxRate = 0.0825
var budget = 50.0

for i in 1...14{
print("Week \(i)")
for day in daysOfWeek {
    let randInt = Int.random(in:0..<8)
    var totalPrice = prices[randInt]+(prices[randInt]*taxRate)+(prices[randInt]*tips[randInt])
    while totalPrice > budget {
        let randInt = Int.random(in:0..<8)
        totalPrice = prices[randInt]+(prices[randInt]*taxRate)+(prices[randInt]*tips[randInt])
        print(totalPrice, randInt, budget)

    }
    let place = restaurants[randInt]
    budget = budget - totalPrice
    print("\(day) meal: \(place), budget now \(budget)")

}
print()
budget += 50
}