Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write 0.9 to the power of 3 (with variables) in Swift

I´m working on a math program in Xcode Command Line Tool and have some troubles writing the maths in coding.

I want the program to to take to variables (p and x) and find the power of them (p^x).

This is my code now:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import Foundation

var x = 3
var p = 0.9

let squared = pow(p, x)

print(squared) 

I get the error: No exact matches in call to global function ‘pow’

Can someone help me solve this ? 😀

>Solution :

You’re running into the issue because the compiler is doing automatic type inference and x and p are inferred to be different types.

Here’s what the compiler infers the types to be:

var x: Int = 3
var p: Double = 0.9

That’s a problem, because there’s no pow function that takes a combination of Int and Double.

Here’s what you probably want:

var x: Double = 3
var p: Double = 0.9

let squared = pow(p, x)

print(squared)

Or, alternately, the compiler can infer x as a Double if you include the decimal:

var x = 3.0
var p = 0.9

In both of the above cases, the compiler uses the pow function that takes Doubles for both arguments.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading