How do you round a double to two decimal places in C?
- User
How do you round a double to two decimal places in C?
- Assistant
In C, you can round a double to two decimal places using the
rint()function from themath.hlibrary. Therint()function rounds a double to the nearest integer, but you can manually apply the required number of decimal places by dividing the number by a suitable power of 10.Here's an example of how to round a double to two decimal places:
#include <math.h> #include <stdio.h> int main() { double input = 123.456789; double rounded_value; // Round the number to two decimal places rounded_value = (input / pow(10, 2)) * pow(10, 2); // Round to nearest even number if the decimal part is odd (optional) if (rounded_value % 2 != 0) { rounded_value = (rounded_value + 1) / 2; } printf("Rounded value: %.2f\n", rounded_value); return 0; }In this example, the input double is first divided by 100 (powers of 10 are used because
doubleis used for the input), and then the result is multiplied by 100 to restore the original scale. Therounded_value % 2 != 0condition checks if the rounded value is odd, and if it is, the value is rounded to the nearest even number. The final output is formatted using the%.2fformat specifier to print the rounded value with two decimal places.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.