0

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 2decimal 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.

OLDY
  • 21
  • 1
  • 7
  • what about `floor(y*100+0.5)/100`, btw, isn't `5.05286` rounded to two decimal places just `5.05`? Just making the last two decimal places zero is not rounding to two decimal places. Your description would fit floor(y+0.5). You don't need condition if you realize that `if x is over 0.5` is the same as `x + 0.5 > 1`. – petrch Jan 19 '21 at 09:29
  • 2
    *I also tried to use the round() function but it doesn't round at all.* Not sure what you mean - did you just use something like `round(y);`? That won't work, but `y = round(y);` *will* work. – Adrian Mole Jan 19 '21 at 09:29
  • 2
    You should provide your attempt with `round`. – Damien Jan 19 '21 at 09:33
  • *"I also tried to use the round() function but it doesn't round at all."* - Then you're doing something wrong – klutt Jan 19 '21 at 14:18

2 Answers2

4

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);
gordon_freeman
  • 366
  • 2
  • 10
1

If you don't want to use any additional header:

    float x = 5.65286;
    x = (int)(x+0.5);
    printf("%.2f",x);
J. Mehri
  • 19
  • 1
  • This has significant drawbacks for large numbers and does not work well for negative numbers. – klutt Jan 19 '21 at 14:31