Challenge: Division int and double
We will not stop on most operations since they work as expected. Instead, let's look at the reasons behind the incorrect result obtained from the division operation. Those are explained in a video below:
It's not just a problem limited to division. When you use operators such as +
, -
, *
, or /
on variables of certain types, the resulting value will have the same type as the operands.
It's important to be mindful of these possibilities and take them into account.
Swipe to start coding
Imagine you're building a taxi meter program: the GPS gives a fractional distance (12.7 km), but the meter rounds it down to a whole number. You need to write a function that calculates the customer's fare.
- Use the existing function
calculatePayment
, which has a return type ofint
and two parameters:double distance_km
— traveled distance.int rate_per_km
— price per kilometer.
- Multiply
distance_km
by 1 to convert it to anint
and assign the result to the variabledistance_km_int
. - Declare a type for
payment_exact
that should store an integer value. - Multiply the distance by the rate per kilometer and assign the result to
payment_exact
. - Return the result.
Soluzione
solution.cpp
Grazie per i tuoi commenti!
single
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 4.35
Challenge: Division int and double
Scorri per mostrare il menu
We will not stop on most operations since they work as expected. Instead, let's look at the reasons behind the incorrect result obtained from the division operation. Those are explained in a video below:
It's not just a problem limited to division. When you use operators such as +
, -
, *
, or /
on variables of certain types, the resulting value will have the same type as the operands.
It's important to be mindful of these possibilities and take them into account.
Swipe to start coding
Imagine you're building a taxi meter program: the GPS gives a fractional distance (12.7 km), but the meter rounds it down to a whole number. You need to write a function that calculates the customer's fare.
- Use the existing function
calculatePayment
, which has a return type ofint
and two parameters:double distance_km
— traveled distance.int rate_per_km
— price per kilometer.
- Multiply
distance_km
by 1 to convert it to anint
and assign the result to the variabledistance_km_int
. - Declare a type for
payment_exact
that should store an integer value. - Multiply the distance by the rate per kilometer and assign the result to
payment_exact
. - Return the result.
Soluzione
solution.cpp
Grazie per i tuoi commenti!
single