0

I expect that if I add 0.5 to a double and then truncate the value to round a double to the nearest integer. However, in the following code it doesn't work:

#include<stdio.h>
int main()
{
  int a,b,d;
  double c;
  a = 54325;
  b = 7858;

  c = a/b;
  c = c+0.5;           /* rounding trick */

  d = (int)c;          /* truncate integer */
  printf("%d\n",d);
  return 0;
} 

54325/7858 should result in 6.91, so if I add 0.5 and then truncate the value, my answer should be 7. However, I get 6 as result. Why?

3
  • Your rounding trick is not a very good way to round numbers, especially when C has its own tested implementations.
    – chris
    Jul 28, 2014 at 16:32
  • So what would you recommend?
    – emjay
    Jul 28, 2014 at 16:46
  • round
    – chris
    Jul 28, 2014 at 16:50

4 Answers 4

4
 c=a/b;

is an integer division as both operands of / are of integer types. This is the case even if here c is of type double.

To have a floating point division you need one operand of the / operator to be of floating point type:

 c = (double) a / b;
1

This is because this expression

c=a/b;

produces an integer result: it does not matter that you assign it to a double - the division of two ints is always an int.

Fix it by adding a cast:

c=(double)a/b;
1
  • Thank you! I'm a rookie, so I still brushing up my basics.
    – emjay
    Jul 28, 2014 at 16:19
1

"54325/7858 should result in 6.91"

No, it does not.

Integer 54,325 divided by integer 7,858, results in integer 6.

There is no .91, because int / int = int.

0
0

Because 54325/7858 is an integer division. There is no rounding involved at all. It just tells you how many times can divisor (7858) fit into divider (54325). Integer division is also coupled to integer remainder so when:

div = a / b;
rem = a % b;

then this holds:

div * b + rem == a

it could never hold if any kind of rounding would have been involved.

If you want rounding, cast at least one value to double (or float) and then use one of these:

#include <math.h>
...
double c = (double)a / b;
double rounded_to_nearest = round(c);
double rounded_up         = ceil(c);
double rounded_down       = floor(c);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.