c - Rounding positive number up two places -
hey guys, i'm trying write program take positive number fractional part , round 2 places.for example 32.4851 round 32.49, , 32.4431 round 32.44.
i lost on 1 , hoping guys me out little bit. have written code , need feedback (won't compile using gcc) using stdio.h , math.h
#include <stdio.h> #include <math.h> double x; int rounded_x; int main (void) { printf ("enter number rounded \n\n\n\n\n"); scanf ("&lf", &x); rounded_x=(int) (x+0.5); return 0; } double scale (double x, int n) { double scale_factor; scale_factor = pow(10, n); return (x*scale_factor); }
the multiply 100, divide 100 solution right. can end deceiving results because of nature of floating-point datatypes. nice round numbers in base-10, "1.23" not translate base-2 floating point storage format. may find rounding "1.2345" ends "1.23" expected, "1.1234" end "1.11989589285982959295892859289582958295" or crazy.
for reason, if kind of accuracy important - if using these rounded numbers in calculation, should consider operating in integers.
for example, when working money, developers work in cents instead of dollars. so, "$1.75" represented "175". guarantees accuracy cent. divide 100 when want display user then.
Comments
Post a Comment