Challenge: Type Casting
Swipe to start coding
In this challenge, you will practice declaring variables of different numeric types and converting between them using explicit type casting. You will calculate the total cost of items in a shopping cart by declaring an int variable for quantity and a double variable for price per item, converting types as needed, and computing the total price.
Follow these steps:
- Declare and initialize an
intvariable calledquantity(set it to 4); - Declare and initialize a
doublevariable calledpricePerItem(set it to 3.75); - Convert
quantityto adoubleand store it in a variable namedquantityAsDouble; - Convert
pricePerItemto anintand store it in a variable namedpriceAsInt; - Calculate the total cost by multiplying
quantityandpricePerItemand store the result in a variable namedtotalCost; - Print all variables and their converted values to the console.
Example output:
Quantity: 4
Price per item: 3.75
Quantity as double: 4
Price per item as int: 3
Total cost: 15
Løsning
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Fantastisk!
Completion rate forbedret til 1.25
Challenge: Type Casting
Sveip for å vise menyen
Swipe to start coding
In this challenge, you will practice declaring variables of different numeric types and converting between them using explicit type casting. You will calculate the total cost of items in a shopping cart by declaring an int variable for quantity and a double variable for price per item, converting types as needed, and computing the total price.
Follow these steps:
- Declare and initialize an
intvariable calledquantity(set it to 4); - Declare and initialize a
doublevariable calledpricePerItem(set it to 3.75); - Convert
quantityto adoubleand store it in a variable namedquantityAsDouble; - Convert
pricePerItemto anintand store it in a variable namedpriceAsInt; - Calculate the total cost by multiplying
quantityandpricePerItemand store the result in a variable namedtotalCost; - Print all variables and their converted values to the console.
Example output:
Quantity: 4
Price per item: 3.75
Quantity as double: 4
Price per item as int: 3
Total cost: 15
Løsning
Takk for tilbakemeldingene dine!
single