Implemented a function that rounds off to the nearest whole number in C language


#include <stdio.h>

//Round up
int roundUp(double n){
	if(n >= 0){ 
		return (int)n + 1;
	}else{
		return (int)n - 1;
	}
}

//Truncate
int roundDown(double n){
	return (int)n;
}

//Rounding
int roundOff(double n){
	double decimal = 0;

	decimal = n - (int)n;

	if(decimal >= 0.5 || decimal <= -0.5){
		return roundUp(n);
	}else{
		return roundDown(n);
	}
}


int main(){
	
	double n;
	int ans = 0;

	printf("Round to the nearest whole number\n");
	printf("Enter a real number:"); scanf("%lf",&n);

	ans = roundOff(n);

	printf("%d\n",ans);

	return 0;
}

There was an easier way to do it.



#include <stdio.h>

int main(){	
    double real;
    double ans;

    printf("Enter a real number:"); scanf("%lf",&real);

	//Rounding
    if(real >= 0){
    	ans = (int)(real + 0.5);
    }else{
    	ans = (int)(real - 0.5);
    }

    printf("%Rounded off result[%f]\n",real,ans);

    return 0;
}

Recommended Posts