Why is this giving me a value of 1?

 
std::cout << (1/1) + (1/2) + (1/3) + (1/4) + (1/5) << std::endl ;
Last edited on
Integer division :+)
How would I tell it the it's a long double?
Nevermind.

The answer is

 
((long double)1/(long double)1)
Dividing two integers will give you an integer in C++. The first term (1/1) results in 1. The rest result in 0.

1
2
std::cout << (1/1) + (1/2) + (1/3) + (1/4) + (1/5) << std::endl;
std::cout << ( 1 ) + ( 0 ) + ( 0 ) + ( 0 ) + ( 0 ) << std::endl;


If you want the result to have a fractional part you should make sure that at least one of the operands is of floating point type (e.g. double). You can do this by including a decimal dot.

 
std::cout << (1.0/1.0) + (1.0/2.0) + (1.0/3.0) + (1.0/4.0) + (1.0/5.0) << std::endl;
Last edited on
Topic archived. No new replies allowed.