scanf() and doubles?
I am having an issue with the following program. This is just a simple program that calculates the surface area/volume of a cylinder. For some reason this executes JUST fine in CodeBlocks. Everything works exactly as it should and I get the correct values.
However, when I try to run it in the IDE that my professor forces us to use I always get 0 for values. If I change all the variables to int and use %d it will compile fine in both, but I lose accuracy. Double is required. Is %lf the correct scanf() function to use for doubles? I have tried many different things and I cannot get it to work properly in the IDE for my class.
Here is the following code:
#define PI 3.141593
double computation(double l, double r)
if (2*r >= l)
printf("These dimensions do not define a valid tank");
double volCYL = (PI * r * r * l);
double volSPH = (4.0/3.0 * PI * r * r * r);
double surfCYL = (2 * PI * r * l);
double surfSPH = (4 * PI * r * r);
printf("A cylindrical tank of length %.3lf and radius %.3lf with inverted spherical\n", l,r);
printf("volume: %.3lf\n", volCYL-volSPH);
printf("surface area: %.3lf\n", surfCYL+surfSPH);
double length = 0;
double radius = 0;
printf("ACME Truck Company\n");
printf("This program will calculate the volume and surface area of the x-11\n");
printf("Enter the length of the tank (feet)");
while (length < 10 || length > 20)
printf("Please enter a value between 10 and 20:");
printf("Enter the radius of the tank (feet)");
while (radius < 3 || radius > 6)
printf("Please enter a value between 3 and 6:");
Any help would be much appreciated!
Yes, "%lg" is correct for doubles for scanf, but you only need "%g" for printf according to printf(3): formatted output conversion - Linux man page.
Originally Posted by Frankie15
EDIT: If that doesn't fix it, tell us what compiler you're using with Code::Blocks that works, and what IDE/compiler you have to use for school.
Thank you SO much anduril.
Ok, I used %lg and %g (ignore code in updated original post. I thought it may have been lf instead of lg so I updated.)
Using %g instead of %lg worked PERFECTLY. Again, thank you!
%lg for scan and %g is working fine now to get whole number values, BUT I am having trouble getting it to display to three decimal places. Wouldn't you just type:
EDIT: It seems using %.3f will work for printing 3 decimal places. Is it acceptable to print an "lg" variable with "%f?
Yes, it's acceptable to use %f for your output. Actually, I almost always see %f used for floats/doubles, and rarely, if ever, see %g or %e, though to be fair, I don't write scientific code, so I don't need scientific notation. Read the link in my previous post carefully, particularly the parts for the "f,F" and "g,G" specifiers if you want all the details.
EDIT: and you're welcome.
Thanks for the link as well. I will use that to review for sure.
Thanks again for your help. Appreciate you taking the time to do so! :)