2015-10-04 21 views
0

下面的等式應該輸出twosFloat爲1,但它返回.8任何人都可以發現我的錯誤嗎?簡單的等式不返回正確的值

int weight = 50; 
int barWeight = 45; 

int weightWithoutBarWeight = weight - barWeight; 

int fortyFives = (weightWithoutBarWeight/2)/45; 
int thirtyFives = ((weightWithoutBarWeight/2) - (fortyFives * 45))/35; 
int twentyFives = ((weightWithoutBarWeight/2) - (fortyFives * 45) - (thirtyFives * 35))/25; 
int tens = ((weightWithoutBarWeight/2) - (fortyFives * 45) - (thirtyFives * 35) - (twentyFives * 25))/10; 
int fives = ((weightWithoutBarWeight/2) - (fortyFives * 45) - (thirtyFives * 35) - (twentyFives * 25) - (tens * 10))/5; 
double twosFloat = ((weightWithoutBarWeight/2) - (fortyFives * 45) - (thirtyFives * 35) - (twentyFives * 25) - (tens * 10) - (fives * 5))/2.5; 
int twos = (int)twosFloat; 

System.out.println(twosFloat); 
+5

錯誤是您正在使用整數除法。 – Tunaki

+0

是的,只需聲明所有變量爲「double」而非「int」。 –

+0

打印出「twos」而不是「twosFloat」。 –

回答

1

所有你需要做的就是將你的一些數字轉換爲float或者double。符號「f」將整數轉換爲浮點數。

int weight = 50; 
int barWeight = 45; 

int weightWithoutBarWeight = weight - barWeight; 

float fortyFives = (weightWithoutBarWeight/2f)/45f; 
float thirtyFives = ((weightWithoutBarWeight/2f) - (fortyFives * 45))/35f; 
float twentyFives = ((weightWithoutBarWeight/2f) - (fortyFives * 45) - (thirtyFives * 35))/25; 
float tens = ((weightWithoutBarWeight/2f) - (fortyFives * 45) - (thirtyFives * 35) - (twentyFives * 25))/10f; 
float fives = ((weightWithoutBarWeight/2f) - (fortyFives * 45) - (thirtyFives * 35) - (twentyFives * 25) - (tens * 10))/5f; 
double twosFloat = ((weightWithoutBarWeight/2f) - (fortyFives * 45) - (thirtyFives * 35) - (twentyFives * 25) - (tens * 10) - (fives * 5))/2.5f; 
int twos = (int)twosFloat; 

System.out.println(twosFloat); 
0

爲了更加清楚起見,您的最後一個二分之一之前的整數部分四捨五入到較低的整數並在小數點後面刪除數據。雖然可以將整數轉換爲雙精度值,但也可以初始化雙精度變量並將其格式化爲2位小數(如下所示)(假設您的原始碼使用雙精度而不是整數)。

System.out.printf(「結果是%1.2f」,twosFloat);

相關問題