Link to home
Start Free TrialLog in
Avatar of strider031598
strider031598

asked on

Rounding Function

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?
ASKER CERTIFIED SOLUTION
Avatar of Motaz
Motaz

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Motaz
Motaz

//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);
}
Avatar of ozo
flt=floor(flt+0.5);  

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

ASKER

Thanks, Motaz!