Reputation: 147
My goal of my program is to cut off pi at a given point as dictated by the user.
I have figured out how to do it, but I cannot figure out how to get rid of the trailing zeroes.
#include <stdio.h>
#include <math.h>
int main()
{
int i,length;
double almost_pi,pi;
printf("How long do you want your pi: ");
scanf("%d", &length);
pi = M_PI;
i = pi * pow(10,length);
almost_pi = i / pow(10,length);
printf("lf\n",almost_pi);
return 0;
}
Let's say user inputs 3, it should return 3.141, but it is returning 3.141000.
Please and thanks!
Upvotes: 1
Views: 191
Reputation: 27125
You need to specify a formatting parameter, the length, as an additional argument to printf:
printf("%.*f\n, length, almost_pi);
This reference states that the .*
means that "The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted."
As an aside, you can use %f
for both doubles and floats with printf, but you still have to use %lf
for doubles with scanf. See here.
Upvotes: 1
Reputation: 66254
Is this what you're trying to do??
#include <stdio.h>
#include <math.h>
int main()
{
int length = 4;
printf("How long do you want your pi: ");
if (1 == scanf("%d", &length))
printf("%.*f\n", length, M_PI);
return 0;
}
Sample Output #1
How long do you want your pi: 4
3.1416
Sample Output #2
How long do you want your pi: 12
3.141592653590
Upvotes: 3