#include <stdio.h>
int main() {
printf("Output = %.4f", trunc(14.23)); // Output = 14.0000
printf("\nOutput = %.4f", trunc(4.831)); // Output = 4.0000
printf("\nOutput = %.4f", trunc(-17.831)); // Output = -17.0000
printf("\nOutput = %.4f", trunc(-22.23)); // Output = -22.0000
return 0;
}
#include <stdio.h>
#include <math.h>
int main(void){
double x,y;
x=trunc(13.345);
y=trunc(-12.456);
printf("x=%lf , y=%lf", x,y);
return 0;
}
The above code will give this output.
x=13.000000, y=-12.000000
#include <stdio.h>
#include <math.h>
int main(void){
float x,y;
x=truncf(13.345);
y=truncf(-12.456);
printf("x=%f , y=%f", x,y);
return 0;
}
Output is here
x=13.000000, y=-12.000000
#include <stdio.h>
#include <math.h>
int main(void){
float x,y;
x=truncl(13.345);
y=truncl(-12.456);
printf("x=%f , y=%f", x,y);
return 0;
}
Output is here
x=13.000000, y=-12.000000
Syntax
trunc(x)
x = input number This example demonstrates how to use trunc() to truncate positive, negative, and zero values.
#include <stdio.h>
#include <math.h>
int main() {
double num1 = 9.75, num2 = -9.75, num3 = 0.0;
printf("trunc(%.2f) = %.2f\n", num1, trunc(num1));
printf("trunc(%.2f) = %.2f\n", num2, trunc(num2));
printf("trunc(%.2f) = %.2f\n", num3, trunc(num3));
return 0;
}
Output:
trunc(9.75) = 9.00
trunc(-9.75) = -9.00
trunc(0.00) = 0.00
---
Allow users to input a number and see its truncated value using trunc().
#include <stdio.h>
#include <math.h>
int main() {
double num;
printf("Enter a number: ");
scanf("%lf", &num);
printf("The truncated value is: %.2f\n", trunc(num));
return 0;
}
Output:
Enter a number: 14.89
The truncated value is: 14.00
---
This example truncates an array of floating-point numbers.
#include <stdio.h>
#include <math.h>
int main() {
double nums[] = {3.14, -2.73, 5.99, -7.01};
int n = sizeof(nums) / sizeof(nums[0]);
for (int i = 0; i < n; i++) {
printf("trunc(%.2f) = %.2f\n", nums[i], trunc(nums[i]));
}
return 0;
}
Output:
trunc(3.14) = 3.00
trunc(-2.73) = -2.00
trunc(5.99) = 5.00
trunc(-7.01) = -7.00