Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Martin Lynnerup
Martin Lynnerup
3,134 Points

Simple function returns stange results

After completing the course "Building a Simple iOS App with Swift" I'm playing around with creating different simple apps. I created the below function to calculate my treadmill speed at the gym, but the values it returns are wrong.

I suspect it might have something to do with how you calculate decimal numbers, but I havn't been able to solve it.

Example: DifficultyLevel: 8 running speed = (18/10) * 8 = 14,4 But the function return is 8

Can you please help me? Thanks!

func Speed(level difficultyLevel:Int) -> Int {
    // difficulty level is from 1-10 where 10 is max

    let topSpeed: Int = 18
    let topSpeedDivided: Int = topSpeed/10
    let runningSpeed: Int = topSpeedDivided * difficultyLevel

    return runningSpeed
}

1 Answer

Hi Martin,

Yes, this is because you are using integers. With integer division, 18/10 is 1; there is only one whole 10 in 18. Then you are multiplying 1 by 8, so the function returns 8.

I'd suggest switching the datatype to Double rather than Int. This will then handle the fractional part of the expressions.

Steve.

Martin Lynnerup
Martin Lynnerup
3,134 Points

Thought I had tried that already, but this time it worked ;)

Thanks a lot!

No problem! :+1: