Lua獲取C 中的double float不精確

2021-09-28 22:17:19 字數 1084 閱讀 6817

lua向c++中傳輸數值,c++部分取為float型別時資料時準確的(此時不能在linux gdb 斷點  p 出資料,否則資料也會不準確,而實際時準確的。)

而lua從c++中獲得float 或者 double資料時,會出現 float 108.032 獲得到lua中時 變為 108.03197994 之類的變化,此時需要呼叫

--從c++來的各類浮點數 都要經過這個函式的精度轉化

function lib:cfloatdataplustoluadata(measured,szbaseclass)

local baseclass;

if(szbaseclass == "float") then

baseclass = 6;

elseif(szbaseclass == "double") then

baseclass = 15;

end

local nmultiple;

local naccuracy;

for nbase=1,baseclass do

naccuracy = 10 ^ nbase;

local xvalue = measured / naccuracy;

if(xvalue < 1.0) then

nmultiple = nbase;

break;

endend

naccuracy = 10 ^ (baseclass - nmultiple);

local decimal = measured * naccuracy;

decimal = (decimal % 1 >= 0.5 and math.ceil(decimal)) or math.floor(decimal);

decimal = decimal / naccuracy;

return decimal;

end

從而使 108.03197994 變為  108.032  

因為float 為6位,不能一味的取小數點後 6為,那樣必讀時錯誤的,float是6位有效,

如果小數點前有5位 ,那麼小數點後只有一位有效,多餘的精度已經丟失

lua中獲取table長度的問題

官方文件是這麼描述 的 取長度操作符寫作一元操作 字串的長度是它的位元組數 就是以乙個字元乙個位元組計算的字串長度 tablet的長度被定義成乙個整數下標n。它滿足t n 不是nil而t n 1 為nil 此外,如果t 1 為nil,n就可能是零。對於常規的陣列,裡面從 1 到n放著一些非空的值的時...

Lua 實現C 中的類

直接上 local mt function class clsname,base local cls base base or mt setmetatable cls,cls.clsname clsname or default cls.base base cls.new function loca...

lua獲取陣列的長度

對於乙個陣列我們通常可以使用 來獲取其長度 tabletest print tabletest 5使用這兩種方法都能得到這個陣列的長度,但是如果 tabletest print tabletest 6 tabletest print tabletest 1 tabletest print table...