Reputation: 41
I tried searching this up on Stack Overflow but couldn't find an answer.
Here is the code:
#include <stdio.h>
int main(void) {
double y;
printf("Enter a number: ");
scanf("%lf", &y);
printf("Your number when rounded is: %.2lf", y);
//If user inputs 5.05286, how can i round off this number so as to get the output as 5.00
//I want the output to be rounded as well as to be 2 decimal places like 10.6789 becomes 11.00
return 0;
}
I want to round a number, for example, if the number is 5.05286
, it should be rounded to 5.00
, and if it is 5.678901
, it will be rounded to 6.00
with 2
decimal places. The number 5.678901
is getting rounded to 5.05
but it should round to 5
. I am aware that I can use floor()
and ceil()
, but I don't think I will be able to round off the answer without conditional statements, which is not the scope of my C
knowledge. I also tried to use the round()
function but it doesn't round at all.
Upvotes: 2
Views: 14800
Reputation: 19
If you don't want to use any additional header:
float x = 5.65286;
x = (int)(x+0.5);
printf("%.2f",x);
Upvotes: 1
Reputation: 419
You need to import <math.h>
header :
#include <math.h> //don't forget to import this !
double a;
a = round(5.05286); //will be rounded to 5.00
This function has analog definitions for every type, which means that you can pass the following types and it'll be rounded to the nearest for every one of them :
double round(double a);
float roundf(float a);
long double roundl(long double a);
Upvotes: 6