emjay
emjay

Reputation: 43

Why does my simple rounding trick not work?

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?

Upvotes: 0

Views: 123

Answers (4)

Jan Spurny
Jan Spurny

Reputation: 5527

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);

Upvotes: 0

abelenky
abelenky

Reputation: 64682

"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.

Upvotes: 1

ouah
ouah

Reputation: 145839

 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;

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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;

Upvotes: 1

Related Questions