#include <stdio.h>
#include <math.h>
/*
============================================================
Convert a decimal-like value to a long in C.
This program demonstrates:
• Conversion using lround(), which rounds to the nearest integer.
• Conversion using a direct cast (long), which truncates toward zero.
• A helper function that prints both results for comparison.
Notes:
• C does not have a built-in decimal type.
• double or long double are used for decimal values.
• lround() follows IEEE rounding rules.
• (long)value truncates the fractional part.
============================================================
*/
/* Converts a floating decimal value to long using rounding */
long convert_decimal_to_long(double value) {
return lround(value);
}
/* Converts a floating decimal value to long using truncation */
long cast_decimal_to_long(double value) {
return (long)value;
}
/* Prints both conversion styles for comparison */
void show_conversions(double value) {
printf("Input decimal: %.4f\n", value);
long rounded = convert_decimal_to_long(value);
long truncated = cast_decimal_to_long(value);
printf("Rounded (lround): %ld\n", rounded);
printf("Truncated (cast to long): %ld\n\n", truncated);
}
int main(void) {
/* Example values to demonstrate behavior */
show_conversions(12.7);
show_conversions(12.3);
show_conversions(-5.8);
show_conversions(42.0); /* already an integer */
return 0;
}
/*
run:
Input decimal: 12.7000
Rounded (lround): 13
Truncated (cast to long): 12
Input decimal: 12.3000
Rounded (lround): 12
Truncated (cast to long): 12
Input decimal: -5.8000
Rounded (lround): -6
Truncated (cast to long): -5
Input decimal: 42.0000
Rounded (lround): 42
Truncated (cast to long): 42
*/