Integer Division
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 16 of 92.
When both values of a division are integers, / gives an integer: the decimal part is dropped.
print(7 / 2) # 3
print(10 / 3) # 3The result is not rounded: 7 / 2 is 3, not 4. With a negative number the decimal part is dropped as well, so -7 / 2 is -3.
When at least one value is a float, the result is a float and keeps its decimal part:
print(7.0 / 2) # 3.5
print(7 / 2.0) # 3.5The same rule applies to variables. To get the exact result from two integer variables, convert one of them with float():
var coins := 7
var players := 2
print(coins / players) # 3
print(float(coins) / players) # 3.5Integer division is useful for whole items: 7 coins shared by 2 players gives each player 3 coins.
Challenge
Easy17 coins are shared by 5 players. The variables total_coins and players are declared for you.
Declare two more variables:
coins_each: the whole number of coins each player gets, using integer division oftotal_coinsbyplayersexact_share: the exact share as a float, usingfloat()ontotal_coinsbefore dividing
The print() lines are already there and output:
Each player gets: 3 coins
Exact share: 3.4Try it yourself
extends Node
func _ready():
var total_coins := 17
var players := 5
# Declare coins_each and exact_share below
# Don't change the lines below
print("Each player gets: ", coins_each, " coins")
print("Exact share: ", exact_share)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler