I’m new to C++ and programming in general . I’m trying out small programs just to get my hand dirty . Below is a program I created for calculating the volume of a cone.
Problem : No matter what I do the output is always an integer . I want to get it to two decimal points accuracy . I’ve tried changing the variables to double and long double to get higher precision and nothing works.
How can I fix this? And why is this happening ? (In detail if possible) I’ve even asked few junior lecturers at UNi so far no one gave me a proper answer.
int main (){
float radius,length,volume ;
const float PI =22/7.0f;
cin >> radius >> length;
volume =1/3.0f *radius*radius*length;
cout << "Volume is " << volume <<endl;
return 0;
}
I’m using g++ on Fedora
EDIT : I Tried this earlyer with inputs like 50 60/70 50 /120 40 which gives integers. Smaller inputs like 3 4 gives decimals.
EDIT : setprecision() works. thanks for everyone for sent this
The program as posted above (adding the missing
#include <iostream>andusing namespace std;) produces several digits after the decimal point for me. If you want it to produce exactly two decimal after the decimal point you need to use something like this:somewhere prior to your output (the latter manipulator is declared in
<iomanip>). The default precision is to use 6 digits and decide how to best distribute them (this may mean the output goes to scientific notation if the values become too big or too small).BTW, don’t use
std::endlunless you really want to flush your output stream. I found several cases where the inappropriate use ofstd::endlturned into a major performance issue.