在數學上,這些結果是相似的,我只是好奇他們的行爲。第一個版本,當我的本地變量被聲明爲一個浮點數時,舍入函數停止顯示小數點後第二位的小數位數。在局部變量聲明爲int的第二個版本中,round
函數四捨五入至小數點後兩位,然後添加一堆零。爲什麼變量類型會導致round
函數的行爲不同?Casting as float vs int returns不同的結果
declare @totalpop float
set @totalpop = (select count(distinct patid) from members)
select @totalpop
select edutext
,COUNT(*) as educationCounts
,round(100.0*COUNT(*)/@totalpop,2)
from
(
select distinct m.patid, e.eduText
from members as m
inner join EducationTable as e on e.eduID = m.education
)x
group by x.eduText
--doesn't圓到小數點後兩位
declare @totalpop int
set @totalpop = (select count(distinct patid) from members)
select @totalpop
select edutext
,COUNT(*) as educationCounts
,round(100.0*COUNT(*)/@totalpop,2)
from
(
select distinct m.patid, e.eduText
from members as m
inner join EducationTable as e on e.eduID = m.education
)x
group by x.eduText
[每個計算機科學家應該知道的關於浮點算術](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Jamiec
+1 to @Jamiec for the epic reference ,甚至脫離主題! ;-) –