简体   繁体   中英

Wanting to generate a random maths function using swift?

I am making an ARKit game (using Swift 4) for younger children learning maths for the first time. I need to make a set of functions to generate a random simple maths question. I know how to get number generation done but trying to also generate a maths operator (+, -, %, *) is proving a challenge.

I initially thought of using an array calling each operator as a string but i need the values to be passed into the actual question so that a correct answer is known.

All it needs to do is produce a case where I can take two variables and put them into a question eg.

var num1 = 0
var num2 = 0


qLabel.text = "\(question)"

num1 = Int.random(in: 0.. < 10)
num2 = Int.random(in: 0.. < 10)

if (operator is a +) {

   question = "\(num1) + \(num2)"
   answer = (num1 + num2)

}

Can anyone help me find a way to go about this?

There is no "magic bullet". For presentation to the user, you will need to choose randomly from a list of operators as strings, eg ["+", "-"] , by generating a random index into the list. For actual calculation, you will have to test for which string it is and write out the corresponding calculation.

One way to do this is to correspond a number with each operator:

let operator = Int.random(in: 0..<4)
let number1 = Int.random(in: 0..<10)
let number2 = Int.random(in: 0..<10)
switch operator {
    case 0: question = "\(number1) + \(number2)"
    case 1: question = "\(number1) - \(number2)"
    case 2: question = "\(number1) / \(number2)"
    case 3: question = "\(number1) * \(number2)"
}

Seeing that this is intended for little kids, you can be a little smart when you generate questions. Using a simple approach like the above might result in questions like "5 / 3" which might confuse some kids who does not know about decimal numbers. So you should probably put the logic to generate each type of question into their own case s.

For subtraction questions, you can check which number is larger first. Then arrange them appropriately to avoid the result being a negative number.

For division questions, you can generate two numbers, and produce a question with the product of the two numbers being divided by one of the numbers. This way you guarantee an integer solution. Something like this:

let number1 = Int.random(in: 0..<10)
let number2 = Int.random(in: 0..<10)
let product = number1 * number2
question = "\(product) / \(number1)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM