Pe*******@gmail.com wrote:

On Oct 22, 9:53 pm, spop...@speedymail.org (Steve Pope) wrote:
PengYu...@gmail.com <PengYu...@gmail.comwrote:
>The usually integer division willroundthe result to the biggest

>integet smaller than the float version division.For example, 10/3 = 3.

>I'm wondering if there is any easy way toroundit to 4 for this case?int a,b,c;

c = (int) ((double)(a/b) + 0.4999999);

Will this introduce errors if a/b=0.50000000000001?

See also rint(), nearbyint() in <cmath>.

How can I guarantee the conversion between float and int won't

introduce any errors?

Thanks,

Peng

Your worried about an insignificant, tiny, non-measureable error whilst

you are attempting to introduce a significant error by suggesting that

10/3 should be 4? Thats a 20% error! What happens when a 20% error gets

propagated?

What are the requirements for that 3 to become a 4? and why?

have you looked at modulus? 10%3, which will result 1 as an adjustment?

Although i still can't understand why.

Do you realize that you'ld have to multiply that doubles's error as

displayed by 1.0 x 10^14 in order for it to impact a cast to an integer

value? In fact, since an integer has both a max and min limitation with

a relatively puny and microscopic valid range, that floating number has

an amazing, mind-boggling count of significant figures.

Here, observe what happens to an integer when it reaches its max

allowed value:

#include <iostream>

#include <limits>

int main()

{

int min = std::numeric_limits<int>::min();

int max = std::numeric_limits<int>::max();

std::cout << "range of an integer on this platform:";

std::cout << "\nmin: " << min;

std::cout << "\nmax: " << max;

std::cout << "\nrollover = " << ++max; // rollover

std::cout << std::endl;

return 0;

}

/* your mileage will vary... i'm running a 64 bit platform

range of an integer on this platform:

min: -2147483648

max: 2147483647

rollover = -2147483648 !!!

*/

Now observe the unadulterated double:

/*

range of a double on this platform:

min: 2.22507e-308

max: 1.79769e+308

*/

thats around 4e616 !!! care to compare a roundoff error of 1.0e-14 to

that range?

floating numbers are not whole numbers and they do typically roundof

the last digit by 0.5 or so. But lets take that into context here.