2009-09-30 67 views
1

顯然這只是代碼的一小部分。是否可以使用printf語句來舍入double對象?

printf("Please enter a positive number that has a fractional part with three or more decimal places\n"); 
scanf("%5.2d", &x); 
printf("The number you have entered is %5.2d\n" ,x); 

這會自動舍入我輸入的數字嗎?還是有另一種方法來做到這一點?

編輯:

printf("Please enter a positive number that has a fractional part with three or more decimal places\n"); 
scanf("%lf", &x); 
x = x + 0.05; 
printf("The number you have entered is %5.2lf\n", x); 

㈣做到了這一點,但是我考慮到有關的printf只是「改變」所說的話的人的方式,讀出。所以這顯然不是正確的方法。我應該實現可能的pow()函數嗎?不知怎的,這會起作用嗎?

EDIT2:

printf("Please enter a positive number that has a fractional part with three or more decimal places\n"); 
scanf("%lf", &x); 
x = x + 0.05; 
printf("The number you have entered is %5.2lf\n", x); 

好的,靜脈得到的地方,如果我開關輸入的數,將舍入到整數的點。 35.21輪到35輪,35.51輪到36輪。等等。

我怎樣才能得到35.2178加到35.22和35.2135加到35.21。 我如何獲得小數的某些冪而不是整數?

+0

是'x'是一個int還是double? – 2009-09-30 20:45:58

+0

我已經嘗試過了,它只在某些時候有效。有沒有另外一種方法可以做到這一點?我對C相對比較陌生。 – Chandler 2009-09-30 20:46:18

+0

X是在這個 – Chandler 2009-09-30 20:46:54

回答

4

你真的不應該在浮點變量中存儲「舍入」值。浮點不準確會毀了這個 - 你的5.10可能會變成5.099999999941892,因爲實現可能無法準確存儲5.10。

作爲一種替代方案,讀取整數,並將其乘以100並將其轉換爲int(將其舍入爲零)。這將保持你的計算準確。

+0

那麼什麼是替代? – Chandler 2009-09-30 20:57:08

+0

增加了一個建議 – hrnt 2009-09-30 21:01:04

+0

我應該在那種情況下使用pow()函數嗎? – Chandler 2009-09-30 21:11:01

0

這是沒有意義的

scanf("%5.2d", &x); 

你不能與DECMAL點後的數字爲整數。如果x是平坦的,那麼奇怪的事情就會發生。如果它是一個整數,爲什麼你在printf中的小數點後兩位。

你究竟想要做什麼?

編輯:

double x; 
printf("Please enter a positive number that has a fractional part with three or more decimal places\n"); 
scanf("%lf", &x); 
printf("The number you have entered is %5.2f\n", x + 0.005); 

我敢肯定的printf只截斷。所以你需要添加0.005來圍繞它。

+0

我試圖圍繞一個小數點後三位數字。 可以說我輸入5.092697436 我想要圓到5.10 – Chandler 2009-09-30 20:48:18

+0

好吧我試過這個,但是它一直在向我吐口水.05。 請輸入一個小數部分帶有三位或更多小數位的正數 5.698 您輸入的數字是0.05 – Chandler 2009-09-30 21:03:25

+1

使用%lf掃描雙數。 %f只適用於浮動。 – hrnt 2009-09-30 21:03:37

2

%.2f」將四捨五入爲2位數。雙精度不是一個整數,並且%d%f不可互換。

+0

那麼,我的問題在哪裏?我應該有%f而不是%d? – Chandler 2009-09-30 20:51:55

+0

@Chandler是的,如果你打印的變量是'double'類型,你應該使用「%f」。 – 2009-10-01 00:04:48

0

printf不會改變數字的值,只是它如何顯示。另一種方法是

#include <math.h> 

// round double x to 2 decimal places 
x = 0.01 * floor(x * 100.0 + 0.5); 
1
{ 

float x; 
float rounded_x; 

printf("Please enter a positive number that has a fractional part with three or more decimal places\n"); 
scanf("%f", &x); 
rounded_x = ((int)(x * 100 + .5)/100.0); 

printf("The number you have entered is %.2f\n", rounded_x); 
return 0; 

} 

謝謝大家誰試圖幫助!我終於明白了

相關問題