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
679 views
in Technique[技术] by (71.8m points)

c++ - Source code to round floating point number

Other than using any inbuilt function like ceil and floor how can you round a floating point number?

I want to convert 2.10 to 2.14-> 2.1 and 2.15 to 2.19 -> 2.2

I wrote some logic but stuck in the middle

    float a = 2.24;
    int b = a*100;
    int result n, i =0;
    while(i>2)
    {
        n = b%10;
        i++;
    }
    if(n >5)
    {
      c = b%10;
      c = c/10 + 1;
    }

I tried lot of inbuild function but all that not workign for my diab compiler

//  totalDist = roundf(totalDist * 10) / 10.0;      
//  totalDist = floor(totalDist * pow(10., 1) + .5) / pow(10., 1);  
    totalDist = floorf(totalDist * 10 + 0.5) / 10;

planning to write my own logic

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
float a = 2.24;
float b = roundf(a*10.0f)/10.0f;//roundf in C99

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

1.4m articles

1.4m replys

5 comments

57.0k users

...