Currently, I am making a program that computes standard deviation. However, the teacher expects all the numbers to be rounded to the nearest hundredth. Anyway, I was wondering if anybody knew of any C functions that accept an argument of type double and return the argument rounded to the nearest hundredth.
here are some examples:
145.453
should round to 145.45
145.459
should round to 145.46
I need specific functions or an example of how to round a number to the nearest hundredth in C.
Continued Rounding ProblemsC
Page 1 of 1
5 Replies - 1693 Views - Last Post: 03 November 2005 - 03:13 PM
Topic Sponsor:
Replies To: Continued Rounding Problems
#3
Re: Continued Rounding Problems
Posted 03 November 2005 - 01:55 PM
I finally figure it out, although it's probably not the most elegant way to do it.
#include <stdio.h>
#include <math.h>
double roundDouble(double number, int num_digits);
int main(void)
{
double number = 34345.54556, rounded;
rounded = roundDouble(number, 2);
printf("Number = %f\nRounded = %f\n", number, rounded);
system("PAUSE");
return 0;
}
double roundDouble(double number, int num_digits)
{
double x, y, roundedNum = 0;
int ctr;
if(num_digits > 0)
{
x = 0.1;
for(ctr = 1; ctr < num_digits; ctr++)
{
x *= 0.1;
}
y = fmod(number, x);
if(y < x * 5 * 0.1)
{
roundedNum = number - y;
}
else
{
roundedNum = number - y + x;
}
}
else
{
x = 1;
for(ctr = 1; ctr <= num_digits*-1; ctr++)
{
x *= 10;
}
y = fmod(number, x);
if(y < x * 5 *0.1)
{
roundedNum = number - y;
}
else
{
roundedNum = number - y + x;
}
}
return(roundedNum);
}
#4
Re: Continued Rounding Problems
Posted 03 November 2005 - 02:33 PM
couldnt you just do
printf("%.2f", number);
?
or did I miss something in the earlier threads?
printf("%.2f", number);
?
or did I miss something in the earlier threads?
#5
Re: Continued Rounding Problems
Posted 03 November 2005 - 02:36 PM
That doesn't actually round the number. It just shows two digits of precision.
#6
Re: Continued Rounding Problems
Posted 03 November 2005 - 03:13 PM
oh you want to store it back into a var.
<dirty code>
<dirty code>
#include <stdio.h>
#include <stdlib.h>
int main(){
double i=5678.45677;
char *tmp;
sprintf(tmp,"%.2f",i);
i=atof(tmp);
return 0;
}
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|