Swift program to get the remainder of float numbers using library function


This tutorial will discuss how to write swift program to get the remainder of float numbers using library function.

A number with fractional component is known as float numbers. For example, 34.5, 2.1, 0.2, etc. We can divide two float numbers with each other to find the remainder and quotient. Remainder is the value left after dividing a number by another number.

Below is a demonstration of the same −

Input

Suppose our given input is −

Num1 = 0.16
Num2 = 0.04

Output

The desired output would be −

Remainder = 0.0

To find the remainder of the float numbers Swift provide the library functions named remainder() and remainder(dividingBy:).

Algorithm

Following is the algorithm −

Step 1 − Declare two Float variables with values

Step 2 − Find the remainder using the library function and store the result into a variable.

Step 3 − Print the output.

Using Remainder(dividingBy:) Method

The remainder(dividingBy: num2) method return the remainder. Here the type of the reminder is also floating-point number.

Syntax

Following is the syntax −

num1.remainder(dividingBy: num2)

Here, num1 is the dividend and num2 is the divisor.

Example

The following program shows how to get the remainder of float numbers using library function.

import Foundation
import Glibc

// Creating two float variables
var num1 : Float = 0.27
var num2 : Float = 0.09

// Finding remainder
var rem = num1.remainder(dividingBy: num2)
print("\(num1) is divide by \(num2). So the remainder is \(rem)")

Output

0.27 is divide by 0.09. So the remainder is 0.0

Using remainder() Function

The remainder() function also return the remainder left by dividing number1 by number2. Here the type of the reminder, number1, and number2 is floating-point number.

Syntax

Following is the syntax −

func remainder<T>(_num1:T, _num2:T) -> T

Here num1 is the divisor and num2 is the dividend. T represent Floating-Point

Example

The following program shows how to get the remainder of float numbers using library function.

import Foundation
import Glibc

// Creating two float variables
var num1 : Float = 0.67
var num2 : Float = 0.03

// Finding remainder
var rem = remainder(num1, num2)
print("\(num1) is divide by \(num2). So the remainder is \(rem)")

Output

0.67 is divide by 0.03. So the remainder is 0.010000031

Updated on: 13-Dec-2022

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements