简体   繁体   中英

Arithmetic operation gives incorrect result

I might be missing something very basic here. But I don't know how to figure out that basic thing. When I set T to 10 and dt to 0.1, I should get the result 101 but I am getting the result as 100. Why is it so?

n_sim_steps = (int)(T/dt) + 1

Furthermore, if I execute this as a watch in eclipse, it returns 101, but in code it results in 100.

It should be

n_sim_steps = (int)(T/dt + 0.5) + 1

You are a victim of precission loss

10 / 0.1 may be 99.999999999999 because of this loss and may be casted back to int as 99 . Adding 0.5 and then casting would make sure that the result is rounded.

You better to use ceil function.

function signature

double ceil (double x);

like ceil(2.3) will results 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM