0

Say I have a double as follows:

double aDouble = 15.6;    

and I want to convert it to three int's as follows:

int x = 1;
int y = 5;
int z = 6;

How would I go about doing this?

GJ.
  • 10,810
  • 2
  • 45
  • 62
JARED
  • 11
  • 1

2 Answers2

4

Since this looks like homework, I will give you 2 clues.

  1. 15.6 = 1 * 10 + 5 * 1 + 6 * 0.1
  2. casting from a double to an int trucates the double.

You should be able to work out the rest.

doron
  • 27,972
  • 12
  • 65
  • 103
0
double aDouble = 15.6;
int tmp = aDouble*10;
int x, y, z;
x = tmp/100;
tmp -= x * 100;
y = tmp/10;
tmp -= y * 10;
z = tmp;
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • A little enlightement may be nice on why this is guaranteed to work. Just checked out the C standard. For one, float to integral is defined to drop the fractional part. You multiply with integer 10, which is converted to double for that operation. If it can not be represented exactly, the nearest value above / below would be taken in an implementation-defined manner. 10 can be represented exactly, so OK. However 15.6 can not, and if the "implementation-defined manner" sided with "below", I would except getting maybe 1; 5; 5 in x; y; z. – Jubatian Dec 08 '14 at 19:22