我想显示切片中正数、负数和零元素的比率。我需要 float32 格式的比率。这是我的代码:
arr := []int32{-2, -1, 0, 1, 2} var negativenumber, positivenumber, zeronumber, totalnumber int32 var negativeratio, positiveratio, zeroratio float32 for i := 0; i < len(arr); i++ { totalnumber += 1 } for i := 0; i < len(arr); i++ { if arr[i] < 0 { negativenumber += 1 } else if arr[i] == 0 { zeronumber += 1 } else if arr[i] > 0 { positivenumber += 1 } } negativeratio = float32(negativenumber / totalnumber) zeroratio = float32(zeronumber / totalnumber) positiveratio = float32(positivenumber / totalnumber) fmt.printf("total number: %d\n", totalnumber) fmt.printf("positive number: %d\n", positivenumber) fmt.printf("negative number: %d\n", negativenumber) fmt.printf("zero number: %d\n", zeronumber) fmt.printf("positive ratio: %f\n", positiveratio) fmt.printf("negative ratio: %f\n", negativeratio) fmt.printf("zero ratio: %f\n", zeroratio)
但是,当我打印变量时,我得到的正数、负数和零数是正确的,但比率是错误的。这是输出:
total number: 5 positive number: 2 negative number: 2 zero number: 1 positive ratio: 0.000000 negative ratio: 0.000000 zero ratio: 0.000000
我做错了什么?
正确答案
您使用的是整数除法而不是浮点除法,浮点除法会丢弃余数并仅返回除法结果的整数部分。
由于 negativeNumber
和 totalNumber
都是 int32
类型,因此 NegativeNumber /totalNumber
执行整数除法,即执行除法并返回结果的下限(即 0)。然后,当您使用 float32(负数/总数)
将其转换为 float32
时,您会得到 0.0
,这是预期的。
为了使用浮点除法,操作数之一必须是浮点类型。为此,您可以使用:float32(负数)/totalNumber
以上是Go - 切片中正数、负数和零数元素的比率的详细内容。更多信息请关注PHP中文网其他相关文章!

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的错误接口定义为typeerrorinterface{Error()string},允许任何实现Error()方法的类型被视为错误。使用步骤如下:1.基本检查和记录错误,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。2.创建自定义错误类型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。3.使用错误包装(自Go1.13起)来添加上下文而不丢失原始错误信息,

对效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,EmparterRorwatchers,InsterTimeouts,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErstopassErrorsErtopassErrorsErrorsFromGoroutInestotheStothemainfunction.2)

在Go语言中,接口的实现是通过隐式的方式进行的。1)隐式实现:类型只要包含接口定义的所有方法,就自动满足该接口。2)空接口:interface{}类型所有类型都实现,适度使用可避免类型安全问题。3)接口隔离:设计小而专注的接口,提高代码的可维护性和重用性。4)测试:接口有助于通过模拟依赖进行单元测试。5)错误处理:通过接口可以统一处理错误。

go'sinterfacesareimpliclyimplysed,与Javaandc#wheRequireexplitiCimplation.1)Ingo,AnyTypewithTheRequiredMethodSautSautsautautapitymethodimimplementalyimimplementsaninternItherninternionterface,callingingSimplicity andficityity.2)

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

开发者应遵循以下最佳实践:1.谨慎管理goroutines以防止资源泄漏;2.使用通道进行同步,但避免过度使用;3.在并发程序中显式处理错误;4.了解GOMAXPROCS以优化性能。这些实践对于高效和稳健的软件开发至关重要,因为它们确保了资源的有效管理、同步的正确实现、错误的适当处理以及性能的优化,从而提升软件的效率和可维护性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版
SublimeText3 Linux最新版

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),