?
Solved

Rounding Function

Posted on 1998-08-18
4
Medium Priority
?
231 Views
Last Modified: 2010-04-01
Is there a function that rounds float variables into
integers?  For example, flt = 2.83; round ( flt ); // flt will now be 3.  If there isn't, do you know how to make one?
0
Comment
Question by:strider031598
  • 2
4 Comments
 
LVL 7

Accepted Solution

by:
Motaz earned 200 total points
ID: 1170619
//Hello Strider, you can write this code, it is very simple !!
// You can easily add 0.5 to the float number and assign it to
// An integer variable

#include <stdio.h>

void main(){
  float f=2.83;
  int i;

  i=f + 0.5;    // Rounding function, just add 0.5 to the float number
              // to be rounded

  printf("\n%d",i);
}
0
 
LVL 7

Expert Comment

by:Motaz
ID: 1170620
//Sorry, last function would'nt work with negative numbers.
//This is the full version of round function. Just copy and //paste.. and it sould work.

#include <stdio.h>

int round(float f){
  if (f>0) return int(f+0.5);    // Posotive number
  else return int(f-0.5);        // Negative number
}

void main(){
  float f;
  int i;

  f=2.83;
  i=round(f);
  printf("\n%d",i);

  f=-2.83;
  i=round(f);
  printf("\n%d",i);
}
0
 
LVL 85

Expert Comment

by:ozo
ID: 1170621
flt=floor(flt+0.5);  

printf("%.0f",2.83);  //will print the rounded value (and should properly round to even for 2.5)
0
 

Author Comment

by:strider031598
ID: 1170622
Thanks, Motaz!
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question