1

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!

dLiGHT
  • 147
  • 1
  • 1
  • 9
  • http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders – Matt Ball Mar 02 '13 at 04:14
  • This [article][1] will help get you started in the right direction. [1]: http://stackoverflow.com/questions/7425030/how-can-i-limit-the-number-of-digits-displayed-by-printf-after-the-decimal-point – jarmod Mar 02 '13 at 04:18
  • 3.141 is the same thing as 3.141000. For that matter, it's also the same as 3.141000000000000000. Your issue is with displaying the value, not what is entered. – Ed S. Mar 02 '13 at 04:35

3 Answers3

3

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
WhozCraig
  • 65,258
  • 11
  • 75
  • 141
1

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.

Community
  • 1
  • 1
1''
  • 26,823
  • 32
  • 143
  • 200
0

printf("%.3f\n",almost_pi); will fix it.