HJ42. 学英语
描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:输入描述
输入一个long型整数
输出描述
输出相应的英文写法
示例1
输入:
22
输出:
twenty two
C 解法, 执行用时: 2ms, 内存消耗: 288KB, 提交时间: 2019-10-06
#include <stdio.h> #include <string.h> #include <stdlib.h> void calc(unsigned int n, int *a) { a[0]=n/(1000*1000*1000); a[1]=(n/(1000*1000))%1000; a[2]=(n/1000)%1000; a[3]=n%1000; //printf("%u %d %d %d %d\n", n, a[0], a[1], a[2], a[3]); } void print(int a) { char *x[]={"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; char *y[]={"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; unsigned flag=0; if(a>=100) { printf("%s hundred", x[a/100]); flag=1; } a%=100; if(a>=20) { if(flag) { printf(" and "); } printf("%s", y[a/10]); a%=10; if(a>0) { printf(" %s", x[a]); } } else if(a>0) { if(flag) { printf(" and "); } printf("%s", x[a]); } } int main() { unsigned int n; while(scanf("%u", &n)!=EOF) { unsigned flag=0; int d[4]={0}; calc(n ,d); if(d[0]!=0) { print(d[0]); printf(" billion"); flag=1; } if(d[1]!=0) { if(flag) { printf(" "); } print(d[1]); printf(" million"); flag=1; } if(d[2]!=0) { if(flag) { printf(" "); } print(d[2]); printf(" thousand"); flag=1; } if(d[3]!=0) { if(flag) { printf(" "); } print(d[3]); } printf("\n"); } return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 296KB, 提交时间: 2021-10-01
#include<stdio.h> #include<string.h> void calc(long n,int *a){ a[3] = n/(1000*1000*1000);//billion a[2] = (n/(1000*1000))%1000;//million a[1] = (n/1000)%1000;//thousand a[0] = n%1000; }; char *x[20] = { "", "one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen" }; char *y[10] = { "","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety" }; char *z[5] = { "hundred","thousand","million","billion" }; void output_int(int a){ int f = 0; if(a >= 100){ printf("%s %s",x[a/100],z[0]); f = 1; } a %= 100; if(a >= 20){ if(f){ printf(" and "); } printf("%s",y[a/10]); a %= 10; if(a > 0){ printf(" %s",x[a]); } }else if(a > 0){ if(f){ printf(" and "); } if(a > 0){ printf("%s",x[a]); } } } int main(){ long n; int a[4],f; while (scanf("%lu",&n)!=EOF) { f = 0; memset(a,0,sizeof(a)); calc(n, a); if(a[3]){ output_int(a[3]); printf(" %s",z[3]); f = 1; } if(a[2]){ if(f){ printf(" "); } output_int(a[2]); printf(" %s",z[2]); f = 1; } if(a[1]){ if(f){ printf(" "); } output_int(a[1]); printf(" %s", z[1]); f = 1; } if(a[0]){ if(f){ printf(" "); } output_int(a[0]); } printf("\n"); } }