2013-03-02 51 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