Solved

Rounding Function

Posted on 1998-08-18
4
212 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 50 total points
Comment Utility
//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
Comment Utility
//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 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
Thanks, Motaz!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now