c++ - Compiler calculating mistake -


i have big homework assignment , got unexpected results, traced down following code

for (int = 0; < 4; i++)     cout << (int)((7163 / (int) pow (10, 4 - - 1))) % 10; 

to 7263 appears on screen, instead of 7163! not happen every 4 digit number , leaves me confused, there wrong logic or compiler's gone nuts. ideas how fix it?

the problem here not compiler, rather standard library implementation of pow function.

but not advisable use (int)(pow(n, k)) compute nk 2 integers.

pow not guaranteed produce exact answer; may out small amount. (actually, accuracy not guaranteed @ all, implementations try not wrong more value of low order bit of result.) since casting (int) truncates rather rounds, tiny error can result in result being off 1. , in case, if result of pow(10,2) ends being 99.999999999999, converting int make 99, , 7163/99 72.

so if insist on using pow, need ensure result rounded rather truncated (see round standard library function). better stick integer arithmetic. example:

for (int = 1000; > 0; /= 10)   std::cout << 7163 / % 10; 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -