Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

How to round up a floating variable in c upto 2/3/4....n digits precision without using <math.h> and printf(".n%f")

float f = 2.8386483,g ;

//Suppose I am having f = 2.8386483..... I want to store k = 2.8.... to n positions where n=a natural //number

//e.g. g= 2.83 to 2 decimal precision/n=2 // g = 2.838 to 3 decimal precision/n=3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...