Reputation: 55
Basically, what I am trying to do is create a random number between 0.001 and 0.999, take that number and multiply by the sublotTons (currently just set for 1000.0), and add that number to one other number (still need to add that bit of code) for the final result.
The issue I am noticing when calling out the numbers to display on screen is that my Random Number will show one thing, but the math doesn't work out.
For example, on my screen currently, it says my Random Number is .943. 1000 * .943 should equal 943 for my Random Sample Tonnage, instead it is telling me that is equal to 525.
Could it be that my code is calling the variable randomNumber twice?
Appreciate the help!
var randomNumber: Double {
let ranNum = Double.random(in: 0.001..<1)
return ranNum
}
let sublotTons = 1000.0
var randomTons: Double {
sublotTons * randomNumber
}
var body: some View {
// Display Random Number
VStack {
Text("Random Number: \(randomNumber, specifier: "%.3f")")
Text("Sublot Tons = 1000")
Text("Random Sample Tonnage: \(randomTons, specifier: "%.0f")")
}
}
}
Upvotes: 2
Views: 109
Reputation: 1215
You can use something like this
var randomNumber: Double = {
let ranNum = Double.random(in: 0.001..<1)
return ranNum
}()
for randomNumber to be calculated and stored one time on start and used later in places you need. You already have this value, not needed to create another one variable to store it again.
Upvotes: 0
Reputation: 1652
Yes, randomNumber
is being called twice.
Since randomNumber
is a computed property, each time you call randomTons
, it will return a new random value.
So, if your intention is to have the same value used, then I suggest to store randomNumber
and make randomTons
a function that receives that stored value:
var randomNumber: Double {
let ranNum = Double.random(in: 0.001..<1)
return ranNum
}
let sublotTons = 1000.0
func randomTons(_ number: Double) -> Double {
sublotTons * number
}
var body: some View {
// Display Random Number
VStack {
let storedRandomNumber = randomNumber
Text("Random Number: \(storedRandomNumber, specifier: "%.3f")")
Text("Sublot Tons = 1000")
Text("Random Sample Tonnage: \(randomTons(storedRandomNumber), specifier: "%.0f")")
}
}
Upvotes: 3
Reputation: 385
You are calling it twice: once here:
Text("Random Number: \(randomNumber, specifier: "%.3f")")
and then, when calculating randomTons here:
Text("Random Sample Tonnage: \(randomTons, specifier: "%.0f")")
Upvotes: 2