rounding to an input value

W

whojustdenyme

I'm new to C...trying to get help on this

#include<stdio.h>
#include<math.h>
int main()
{
int decVal; //DECIMAL VALUE
int round; //# OF PLACES TO ROUND
float a; //ANSWER AFTER ROUNDING
float x;
float y;

printf("Enter a number as a decimal value (ie. 3.1459): ");
scanf("%d", &decVal);
printf("Enter the number of places to round (ie. 3): ");
scanf("%d", &round);

printf("%d",decVal);

printf("The number %d rounded to %d decimal places is %f", decVal,
round);
return(0);
}
 
K

Konstantin Miller

whojustdenyme said:
I'm new to C...trying to get help on this

#include<stdio.h>
#include<math.h>
int main()
{
// you have to declare decVal as float or double
// int decVal; //DECIMAL VALUE
float decVal;
int round; //# OF PLACES TO ROUND
float a; //ANSWER AFTER ROUNDING
float x;
float y;

printf("Enter a number as a decimal value (ie. 3.1459): ");
// and to use %f to scan it
// scanf("%d", &decVal);
scanf("%f", &decVal);
printf("Enter the number of places to round (ie. 3): ");
scanf("%d", &round);
// the same here
// printf("%d",decVal);
printf("%f", decVal); // and here
// printf("The number %d rounded to %d decimal places is %f", decVal,
// round);
// see below how you could define ROUND
printf("The number %f rounded to %d decimal places is %f", decVal,
round, ROUND(decVal));
return(0);
}

Hi!

I guess it is not so easy to do without losing significant precision!

You could do it like this

// floor is from math.h
#define JUST_ROUND(x) floor((double)(x)+0.5)
#define ROUND(x,n) (JUST_ROUND((double)(x) * pow(10,n)) / pow(10,n))

but this would not work for all x because of the division after calling
fround
and
if x is double than you may lose about n significant precision digits and
if x is float and n>9 you may lose about 16-7-n significant precision
digits.

Konstantin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top