-2

I want to print only the sqrt that are in the int form (1,2,3,4,5) only numbers who are sqrt but I don't have the right code to do that.Thank you in advance

I tried to use if statement with I == int print but no didn't succeed

I want the program to skip doubles and print only int

  • 1
    Why the down-vote? For somebody very new to programming, data types can be confusing, and even expressing what you are trying to do can be hard. Let's give new posters some slack! – Duncan C May 31 '23 at 02:09
  • @DuncanC That was exactly my thinking. It seems like a very reasonable question, although I suspect people are responding negatively because it doesn't include the failing code example or any error details. The formatting is also pretty wonky. – Alexander May 31 '23 at 02:24

1 Answers1

2

If you're using sqrt(), Double.squareRoot(), etc., the resulting value's type will always consistently be a Double, regardless of whether it's a whole number or not.

Checking if an Int (e.g. result is Int) will always be false, and the compiler will tell you that:

import Foundation

print(sqrt(4) is Int) // warning: cast from 'Double' to unrelated type 'Int' always fails

What you need to do is check if the result you you get is a whole number:

import Foundation

print(sqrt(4).remainder(dividingBy: 1) == 0) // true
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Will taking the square root of perfect squares return exact values, or will there be rounding error such that sqrt(16) is not exactly 4? – Duncan C May 31 '23 at 02:02
  • I just tried it an it worked. (voted) – Duncan C May 31 '23 at 02:05
  • @DuncanC It'll start failing at some point, but it's true all the way up to at least 2^53, (which is the [last consecutive whole number that's precisely representable with a `Double`](https://stackoverflow.com/a/1848762/3141234), which is `Double(sign: .plus, exponent: Double.significandBitCount + 1, significand: 1)`), equal to `9,007,199,254,740,992`) – Alexander May 31 '23 at 02:20
  • 1
    I think 2^53 is pretty good. It would take... a while to iterate that many values. – Duncan C May 31 '23 at 12:45