trunc() Function 🎯Welcome to a comprehensive guide on the trunc() function in C programming! In this tutorial, we'll explore what the trunc() function is, its usage, and examples. Let's dive in!
trunc() Function 📝The trunc() function is a built-in function in C that is used to get the integer part of a floating-point number. This function rounds the floating-point number down to its nearest integer towards zero.
trunc() Function 📝The syntax for the trunc() function in C is simple:
#include <math.h>
double trunc(double number);trunc() Function Works 💡The trunc() function works by stripping off the decimal part of a floating-point number. For example, if we apply trunc() to the number 3.715, it will return 3.
Let's see some practical examples to understand the trunc() function better:
#include <stdio.h>
#include <math.h>
int main() {
double num1 = 3.715;
double num2 = -2.345;
printf("The integer part of 3.715 is: %.0f\n", trunc(num1));
printf("The integer part of -2.345 is: %.0f\n", trunc(num2));
return 0;
}Output:
The integer part of 3.715 is: 3
The integer part of -2.345 is: -2
Consider a scenario where we want to calculate the number of items in a shopping cart, given their prices as floating-point numbers. Using the trunc() function, we can round down the floating-point values to get the integer number of items.
#include <stdio.h>
#include <math.h>
int main() {
double totalCost = 123.456;
int items = trunc(totalCost);
printf("The total number of items is: %d", items);
return 0;
}Output:
The total number of items is: 123
What does the `trunc()` function do in C programming?
That's it for our tutorial on the trunc() function in C programming! Stay tuned for more in-depth C programming lessons at CodeYourCraft. Happy coding! 💡