This is a Program to convert an Array of Double which has a certain sum to an array of Int with the same sum

We need to convert a double array : {19.75, 27.5, 14.25, 38.5} to Int array with same sum

The problems input has simple rules:

1. The array has even number of number

2. The number of occurrence of a double with 0.5 is always even number of times

3. The sum is always of precision type XX.00000

Well overall this is a very simple problem , nothing too extraordinary.This was a blitz problem which a group of friends formulated instantly and with a solution to be submitted within 10 minutes.

It was no surprise everyone worked around their ceil’s and floor’s knowledge and typecasting knowledge to submit code within 5 minutes.

Anyways this is a code in C which was almost similar to most of them who submitted.( The same flavor and thinking)

#include "stdio.h"
#include "math.h"
int main()
{
double arrayA[4] = {19.75, 27.5, 14.25, 38.5};
int i;
for ( i=0; i<4;i++)
{
int intpart = (int)arrayA[i];
double decpart = arrayA[i] - intpart;
if( decpart > 0.5)
{
arrayA[i]=(int)ceil(arrayA[i]);
}
else if( decpart < 0.5)
{
arrayA[i]=(int)floor(arrayA[i]);
}
else if( decpart == 0.50000)
{
if( intpart%2 == 1)
{
arrayA[i]=(int)ceil(arrayA[i]);
}
else if( intpart%2 == 0)
{
arrayA[i]=(int)floor(arrayA[i]);
}
}
}
for(i=0;i<4;i++)
{
printf("%d\n",(int)arrayA[i]);
}
return 0;
}

OUTPUT:

laptop:~$ ./a.out

20

28

14

38

Eventually, the take away from this article is the knowledge of using Ceil, floor and some basic typecasting.

Efficient , quicker and shorter code are welcome to be sent as comments !

### Like this:

Like Loading...

*Related*

yeah ! thanks

Thanks for the help dude.. coming up with a workaround in 10mins is a good achievement given the situation I was in… here’s the code I am using.

i used a flag to alternate ceil and floor b/w xx.5 values and Round function for other numbers. code is in java

Eventually the problem turned out to be simple, but given the time you had , you did it get it right. Thanks