Sunday, July 12, 2009

Volume = (radius * radius * radius) * (static_cast<double> (4/3)) * (PI) why wont this work correctly in c++

Why wont this work correctly, i need the 4/3 to be 1.33333..., but it keeps cutting it down to an integer and making it 1. Why is this?

Volume = (radius * radius * radius) * (static_cast%26lt;double%26gt; (4/3)) * (PI) why wont this work correctly in c++
declare a variable as double of float first then say for example





value=4/3





now use the var value in the equation instead of 4/3





and c++ dont use bodmas so its calculating order is not like your calculator u might want to do the calculations in diferent lines like first





v1=r*r*r





then





v2=v1/ watever
Reply:You might need to declare a variable or constant first as a float or something. Doesn't C++ treat numbers as integers by default?





HTH
Reply:double volume,radius;





volume = 4/3*(PI)*(radius * radius * radius);





Double operations result double by default. But if you are declaring radius as int and volume as int or float it will not type cast to double and will truncate the result to int





Regards,


Robert


Manchester Info Services


http://www.manchesterinfoservices.com
Reply:Because inside the parens for (4/3) the compiler thinks those are ints. Put it as (4.0/3.0) and see how that does.


No comments:

Post a Comment