+ 1

Hello, I used Class to find the Volume of a sphere by using the rule: volumeSphere=3/4*π*r³ but i dont know why the output is 0

here i set r=4 & pi=3.14 please could someone tell me why the output is 0 ??! #include <iostream> using namespace std; class vol{ private: int r; float pi; int volume; public: void initialize(); void calc(); void showdata(); }; void vol::initialize(){ r=4; pi=3.14; } void vol::calc(){ volume=(3/4)*pi*r*r*r; } void vol::showdata(){ cout<<"volume of sphere is: "<<volume; } int main() { vol v; v.initialize(); v.calc(); v.showdata(); return 0; }

23rd Jan 2018, 4:29 PM
RiGeL
RiGeL - avatar
2 odpowiedzi
+ 2
First of all, the voume of a sphere is (4πr³)/3. Secondly, you may get an incorrect answer as the result if division of two ints is an int by default, and numbers between (0,1) are rounded off to 0 for saving in an integer. Thus the result became 0. So you need to cast the return type to double or use type promotion. Eg = Type Promotion : 4.0/3*3.14*r*r*r; // Here the compiler automatically // returns a float for you. Eg = Type Casting : float(4/3)*3.14*r*r*r; //or static_cast<float>(4/3)*3.14*r*r*r; // Here the compiler is forced // to return a float even when the // expected return value is int.
23rd Jan 2018, 4:49 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
@Kinshuk thank u bro
23rd Jan 2018, 9:27 PM
RiGeL
RiGeL - avatar