- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a one line C function to round floating point numbers
Here we will see how to write one-line C function, that can round floating point numbers. To solve this problem, we have to follow these steps.
- Take the number
- if the number is positive, then add 0.5
- Otherwise, subtract 0.5
- Convert the floating point value to an integer using typecasting
Example
#include <stdio.h> int my_round(float number) { return (int) (number < 0 ? number - 0.5 : number + 0.5); } int main () { printf("Rounding of (2.48): %d
", my_round(2.48)); printf("Rounding of (-5.79): %d
",my_round(-5.79)); }
Output
Rounding of (2.48): 2 Rounding of (-5.79): -6
Advertisements