4 Replies
      Latest reply on May 28, 2017 1:24 AM by John368
      jdavidg9 Level 1 Level 1 (0 points)

        HI

         

        I'm a begginer and have a litle problem with a variable declaration

         

        var nNum3:Float = 5.2

        var nNum4:Float = 1.000

        var nREnt : Int  = nNum1 % nNum2

        var nRes1 : Float  = nNum3 % nNum4  // this line send me error " % is unavailable: use truncating remainder instead " why?

         

        xcode is 8.3.2 version

         

        somebody can help me please?

         

        Thanks

        • Re: Var declarations
          QuinceyMorris Level 8 Level 8 (6,050 points)

          The problem is a practical one, that there's no widespread agreement about what the % operator should do. It calculates a remainer, or a modulus, and it produces a positive result, or a negative result, or a result with the same sign as … whatever, it rounds, it truncates, towards the origin, towards positive infinity, towards negative infinity.

           

          For those reasons, the designers of Swift decided to disallow the use of operator % with floating point numbers. Instead, you use one of the "remainder" functions:

           

               developer.apple.com/reference/swift/floatingpoint

           

          to say what you mean.

          • Re: Var declarations
            jorisvm Level 2 Level 2 (40 points)

            Hi,

             

            this might help:

            var nNum3:Float = 7.0
            var nNum4:Float = 4.0
            var nREnt  = nNum3.truncatingRemainder(dividingBy: nNum4)
            print("Float - Reaminder after division:\(nREnt), type: \(type(of:nREnt))")
            
            let nNum1:Int = 7
            let nNum2:Int = 4
            let nRest = 7 % 4
            print("Int - Reaminder after division:\(nRest), type: \(type(of:nRest))")
            
            
            

             

            Console output:

            Float - Reaminder after division:3.0, type: Float

            Int - Reaminder after division:3, type: Int

             

            Have fun,

            Joris

            • Re: Var declarations
              John368 Level 1 Level 1 (0 points)

              Remainder Operator % is used only for values of type Int

               

              If you write

               

              var nRes1 : Int  = nNum3 % nNum4
              
              

               

              then there will be no error