Double.

Apr 10, 2013 at 7:12pm
Hey everyone

I am trying to write a c++ program and i will like to define r as r=pow((1+(R/100)),1/365)-1. R is variable we type in.

But my teacher has written: r=pow((1+(R/100)),(double)1/365)-1. Why has he written double? I don't understand?
Apr 10, 2013 at 7:18pm
because he is casting the result of integer division. 1/365 = 0.002739726027397260273972602739726. but since its integer division, the result is zero. But by casting it as a double, you get the decimal places.
Apr 10, 2013 at 7:18pm
closed account (o3hC5Di1)
Hi there,

The (double) is what we call a C-style cast.

Both 1 and 365 are integers, so dividing them would give you an integer result, meaning, a result without any floating point numbers. In this case however, you do want floating point values.

In order to do so it suffices to make one of the two numbers a "more precise" data type, such as double.
In this case 1 is explicitly casted to a double by you, the programmer, which will cause the compiler to implicitly cast the 365 to a double also.

This way, you get a double by double division, returning a double result.

For more information on casts, please refer to: http://cplusplus.com/doc/tutorial/typecasting/
You will see there that the use of c-style casts is discouraged, and ofr this case, c++ 's static_cast<double>(1) is preferred.

Hope that helps.

All the best,
NwN
Apr 10, 2013 at 9:07pm
It would be simpler to put a .0 at the end of the numbers, as this would force them to be treated as doubles anyway. The cast is more writing.
Topic archived. No new replies allowed.