栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在保留整数和的同时将浮点数舍入为整数?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在保留整数和的同时将浮点数舍入为整数?

这是应该完成任务的一种算法。与其他算法的主要区别在于,此算法始终按正确的顺序舍入数字。 最小化舍入误差。

该语言是一些伪语言,可能源自Javascript或Lua。应该说明一下。注意一个基于索引的索引(对于循环,x到y更好。

// Temp array with same length as fn.tempArr = Array(fn.length)// Calculate the expected sum.arraySum = sum(fn)lowerSum = 0-- Populate temp array.for i = 1 to fn.lengthf    tempArr[i] = { result: floor(fn[i]),   // Lower bound        difference: fn[i] - floor(fn[i]),  // Roundoff error        index: i }   // Original index    // Calculate the lower sum    lowerSum = lowerSum + tempArr[i].resultend for// Sort the temp array on the roundoff errorsort(tempArr, "difference")// Now arraySum - lowerSum gives us the difference between sums of these// arrays. tempArr is ordered in such a way that the numbers closest to the// next one are at the top.difference = arraySum - lowerSum// Add 1 to those most likely to round up to the next number so that// the difference is nullified.for i = (tempArr.length - difference + 1) to tempArr.length    tempArr.result = tempArr.result + 1end for// Optionally sort the array based on the original index.array(sort, "index")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号