Without using math.h, or printf(“.n%f”), the other answer will work for you.
But regarding your phrase I want to store k = 2.8.... to n positions. It may be interesting to you that this has less to do with rounding than it has to do with type
, and how much memory is required to store each type.
float
, double
and long double
require differing amounts of memory to store the precision (numbers to the right of ".") required by the type, regardless of how you format them for display. That is:
A displayed representation of a float
may look like 2.83
while in memory, a float
will contain memory sufficient to 7 digits precision 2.8368361
(on 32 bit system)
And for a type double
representation of the same number might stored as 2.836836100000001
.
Again, the way a number has little to do with how it is stored.
Edit: (Rounding a float to n decimal places)
#include <ansi_c.h>//I did not realized that this header INCLUDEs math.h, oops
int main(void)
{
int p;
float a,c;
printf("Enter the floating point value:-");
scanf("%f",&a);
printf("Enter the precision value:-");
scanf("%d",&p);
if(a>0)
{
c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
printf("Value Rounding Off:-%f",c);
}
else
{
c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
printf("Value Rounding Off:-%f",c);
}
getchar();
getchar();
}
From HERE (thanks to H. Gupta)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…