Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Thursday, 28 March 2019

Round off

Write a one-line C function to round floating point numbers

Algorithm: roundNo(num)1. If num is positive then add 0.5.
2. Else subtract 0.5.
3. Typecast the result to int and return.

Example:num = 1.67, (int) num + 0.5 = (int)2.17 = 2
C program:
/* Program for rounding floating point numbers */
# include<stdio.h>

int roundNo(float num)
{
    return num < 0 ? num - 0.5 : num + 0.5;
}

int main()
{
    printf("%d", roundNo(-1.777));
    getchar();
    return 0;
}

0 comments:

Post a Comment