codescracker
c

C Program to Round off Decimal or Floating-point Number



« C Tutorial C Examples »

In this tutorial, we will learn about how to create a program in C that will ask from user to enter any number (any real or floating-point number) to round it off to its nearest integer. For example, if user has provided 23.43 as input, then the program will output its nearest integer value that will be 23. Let's take a look at the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    float num;
    int tempCheck, roundNum, tempNum;
    printf("Enter the number: ");
    scanf("%f", &num);
    if(num>0)
    {
        tempNum = num*10;
        tempCheck = tempNum%10;
        if(tempCheck>=5)
        {
            roundNum = num;
            roundNum++;
        }
        else
        {
            roundNum = num;
        }
        printf("\nWhole number after rounding off the given real number = %d", roundNum);
    }
    else if(num<0)
    {
        num = -(num);
        tempNum = num*10;
        tempCheck = tempNum%10;
        if(tempCheck>=5)
        {
            roundNum = num;
            roundNum--;
        }
        else
        {
            roundNum = num;
        }
        printf("\nWhole number after rounding off the given real number = -%d", roundNum);
    }
    else
    {
        printf("\nThe given number is 0");
    }
    getch();
    return 0;
}

As the above program was written under Code::Blocks IDE, therefore after successful build and run, you will get the similar output as given below. This is the first snapshot of the sample run:

c program round off integer

Now supply any real number say 37.5 and press ENTER key to see the nearest integer (whole number) value of the given real number:

round off to nearest integer

Here is another sample run of the above program, this time let's suppose user has provided the real number say -25.56 as input:

rounding off to nearest value c program

Here are the list of some main steps used in above program:

C Online Test


« C Tutorial C Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker