2013-03-02 54 views
1

我的程序目标是在用户指定的给定点切断pi。如何自动摆脱尾随零?

我已经想出了如何做到这一点,但我不知道如何摆脱尾随零。

#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; 
} 

假设用户输入3,它应该返回3.141,但它返回3.141000。

请和谢谢!

+0

http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders – 2013-03-02 04:14:20

+0

此[文章] [1]将帮助您开始正确的方向。 [1]:http://stackoverflow.com/questions/7425030/how-can-i-limit-the-number-of-digits-displayed-by-printf-after-the-decimal-点 – jarmod 2013-03-02 04:18:17

+0

3.141和3.141000是一样的。对于这个问题,它也和3.141000000000000000一样。您的问题是显示值,而不是输入的内容。 – 2013-03-02 04:35:48

回答

3

这就是你想要做的?

#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; 
} 

样本输出#1

How long do you want your pi: 4 
3.1416 

样品输出#2

How long do you want your pi: 12 
3.141592653590 
+0

我不敢相信这是简单的....谢谢! – dLiGHT 2013-03-02 05:07:40

0

printf(“%。3f \ n”,almost_pi);将解决它。

+0

他必须使它基于用户输入,而不是静态地始终设置为'3'。 – eazar001 2013-03-02 04:22:36

1

需要指定的格式化参数,长度,作为附加参数给printf :

printf("%.*f\n, length, almost_pi); 

This reference指出.*表示“精度未在格式字符串中指定,而是作为必须格式化的参数前面的附加整数值参数”。

顺便说一句,您可以使用%f用于printf的双打和浮动,但您仍然必须使用%lf作为scanf的双打。见here