+ 1
using double
I m writing this code int main() { double time = 5/2; cout << time ; return 0; } and is giving a result of 2 why is it happening, and how would I get result 2.5
3 Respuestas
+ 3
5 divided by 2 is 2 with a % of 1. That's why you got 2, you're doing division.
Use a floating decimal point for doubles.
Example (based upon 5/2 fraction):
double time = 2.5;
+ 3
Try this:
double time = 5.0/2.0;
or
double time = 5.0/2;
😊😊
+ 3
lol Maybe Lokesh is right and I am an idiot. :D I thought 5/2 was just your weird way of avoiding decimals. haha As Cool Codin said though, if you want to use doubles in division, don't forget the decimal and it'll work as you think it should.
To explain his second example, the 5.0 will cause the 2 to be converted to a double also. This is called type casting. You can do it implicitly or explicitly.
Another example:
double time = (double) 5/2;
^That'll return 2.5 also by casting the double type onto the integers before calculation.