Complementary task for topic: 1

M Nemeth · 2023-08-29 15:21:04.604221'

scanf: double II.

scanf: double II.

Task: Calculate the total cost of an order:
Write a C program that prompts the user to enter the quantity and price per unit of an item using scanf(), and calculates the total cost of the order. Display the total cost using printf().

Hint: You need to use %lf to scan double precision floats.
Try out what happens when you forgot and use %f!

Solution
#include 

int main() {
    double quantity, pricePerUnit;
    
    printf("Enter the quantity of the item: ");
    scanf("%lf", &quantity);
    
    printf("Enter the price per unit: ");
    scanf("%lf", &pricePerUnit);
    
    double totalCost = quantity * pricePerUnit;
    
    printf("The total cost of the order is %.2lf.\n", totalCost);
    
    return 0;
}



Explanation
In this example, the program uses printf() to prompt the user to enter the quantity and price per unit of an item. The scanf() function is used to scan the input from the user and store it in the quantity and pricePerUnit variables. The program calculates the total cost of the order by multiplying the quantity by the price per unit and stores it in the totalCost variable. Finally, it uses printf() to display the total cost in the specified format.
< < previous    next > >