### Thread: C code help needed

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2003
Posts
53
Rep Power
12

#### C code help needed

I need for the last number to be 0
Code:
```
#include<stdio.h>

double round (double);

int main(void)  {
double orig;

printf("\nEnter a floating point number to be rounded: ");
scanf("%lf",&orig);

printf("\n%.6lf rounded on the fourth decimal place is"
"\n%.5lf\n", orig,round (orig));

return(0);
}
double round (double num)  {
int remainder,modder;
double newnum,rounder, roundednum, numberdec;

/*rounding calculations*/
numberdec = (num - (int)num);
rounder = (int)numberdec * 1000;
modder = (int)rounder % 10;

/*rounding up and adding to the number if above .5*/
if (modder >= 5){
rounder++;
rounder = rounder / 1000;
newnum = rounder + (num - numberdec);
return(newnum);
}
}```
for example if you enter 1.1111111111(ten 1's after decimal) the output should be ..

1.111111 rounded on the fourth decimal place is
1.11110.

but i get 1.11111. What am I doing wrong??

-gman932
2. Set the precision with the appropriate number of decimal places.

Example:

Code:
```#include<stdio.h>

//precison here is the number of decimal places
//default is 4
double round (double num, int precision){
int i,remainder,modder,roundby=1;
double newnum,rounder, roundednum, numberdec;

if (precision < 0 || precision > 9)
roundby = 1000;
else{
for (i=0; i<precision; i++)
roundby *= 10;
}
/*rounding calculations*/
numberdec = (num - (int)num);
rounder = (int)(numberdec * roundby);
modder = (int)rounder % 10;

/*rounding up and adding to the number if above .5*/
if (modder >= 5){
rounder++;
}

rounder = rounder / roundby;
newnum = ((int)num) + rounder;
return(newnum);
}

int main(void)  {
double orig, rounded;
int i;

orig = 1.23456789;
for (i=-1; i<11; i++){/* -1 and 10 shows the default */
rounded = round(orig, i);
printf("%.9lf rounded on the %2d decimal place is"
" %.9lf\n", orig, i, rounded);
}

return(0);
}```
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2003
Posts
53
Rep Power
12
I need to do it without setting precision .....the default is 4 ....that is standard. There should be a easier way without all that , just by using mod or something.