Complementary task for topic: 1
M Nemeth · 2023-08-29 15:21:04.604221'
scanf: double I.
scanf: double I.
Task: Calculate the area of a rectangle:
Write a C program that prompts the user to enter the length and width of a rectangle using scanf() and calculates its area in double precision. Display the area 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 length, width;
printf("Enter the length of the rectangle: ");
scanf("%lf", &length);
printf("Enter the width of the rectangle: ");
scanf("%lf", &width);
double area = length * width;
printf("The area of the rectangle is %.2lf.\n", area);
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter the length and width of a rectangle. The scanf() function is used to scan the input from the user and store it in the length and width variables. The program calculates the area of the rectangle using the formula length * width and stores it in the area variable. Finally, it uses printf() to display the area in the specified format.