Welcome to Rooeye's blog

任意数字(万亿级别以下)转换为英文表示

golang rooeye 530℃ 0评论

逻辑不复杂,但是挺考验编程能力的,万亿(trillion)以下的数字都可以表示,一些比较特殊的case和百度翻译的结果对了很多次 , 数字转化为中文思路差不多 。

package main

import(
	"fmt"
	"math"
)

func oneToNineteen(num int64){
    exps := []string{"one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}
    fmt.Print(exps[num-1])
}

func twentyToNinetyNine(num int64){
	if num<20 {
		zeroToNineteen(num)
		return
	}
	a,b := num/10,num%10
	exps := []string{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}
	fmt.Print(exps[a-2])
	if b!=0 {
		fmt.Print(" ")
		zeroToNineteen(b)
	}
}

func oneHundredTo999(num int64){
	if num<100 {
		twentyToNinetyNine(num)
		return
	}
	exps := " hundred"
	a,b := num/100,num%100
	zeroToNineteen(a)
	fmt.Print(exps)
	if b!=0 {
		fmt.Print(" and ")
		twentyToNinetyNine(b)
	}
}

func oneThousandTo999999(num int64){
	if num<1000 {
		oneHundredTo999(num)
		return
	}
	exps := " thousand "
	a,b := num/1000,num%1000
	oneHundredTo999(a)
	fmt.Print(exps)
	if b!=0 {
		oneHundredTo999(b)
	}
}

func oneMillionTo999999999(num int64){
	if num<1000000 {
		oneThousandTo999999(num)
		return
	}
	exps := " million "
	a,b := num/1000000,num%1000000
	oneHundredTo999(a)
	fmt.Print(exps)
	if b!=0 {
		oneThousandTo999999(b)
	}
}


func oneBillionToInt32Max(num int64){
	if num<1000000000 {
		oneMillionTo999999999(num)
		return
	}
	exps := " billion "
	a,b := num/1000000000,num%1000000000
	oneHundredTo999(a)
	fmt.Print(exps)
	if b!=0 {
		oneMillionTo999999999(b)
	}
}

func numToEng(num int64){
	if num==0 {
		fmt.Println("zero")
		return
	}
	if num<0 { fmt.Print("negative ") } //注:int64最小值在取绝对值后会发生越界,数字太大这里不单独处理了 num = int64(math.Abs(float64(num))) if num>1000 && num%1000<100{
		num_2 := num%1000
		num_1 := num - num_2
		oneBillionToInt32Max(num_1)
		fmt.Print("and ")
		twentyToNinetyNine(num_2)
		fmt.Println()
		return
	}
	oneBillionToInt32Max(num)
	fmt.Println()
	
}

func main(){
	for{
		var num int64
		_,err := fmt.Scan(&num);
		if err != nil{
			fmt.Println("error")
			return
		}
		numToEng(num)
	}
}

运行结果:

转载请注明: Jinkun 的博客 » 任意数字(万亿级别以下)转换为英文表示

喜欢 (1)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址