题解 | #人民币转换#

人民币转换

http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b

具体注释写在code中
#include<stdio.h>
#include<string.h>

int main(){
    char up_digit[9][5] = {"壹","贰","叁","肆","伍","陆","柒","捌","玖"};
    char up_unit[14][5] =  {"仟","佰","拾","亿","仟","佰","拾","万","仟","佰","拾","元","角","分"};
    double money;
    scanf("%lf",&money);
    long money_tmp = (long)(money*1000);
    long r = money_tmp%10;
    if(r>5)
        money_tmp = money_tmp/10+1;
    else
        money_tmp = money_tmp/10;
    int num[100];
    int idx1 = 0;
    while(money_tmp>0){
        num[idx1++] = money_tmp%10;
        money_tmp = money_tmp/10;
    }
    char out[100];
    int offset = 0;
    for(int i = 0;i<idx1;i++){
        // 分角处理
        if(num[0]==0&&num[1]==0 && i==0){
            offset += sprintf(out+offset,"%s","整");
            i = 1;
            continue;
        }
        if(i<=1){ // 分 角不加零
            if(num[i]==0)
                continue;
            else{
                offset += sprintf(out+offset,"%s",up_unit[13-i]);
                offset += sprintf(out+offset,"%s",up_digit[num[i]-1]);
                 continue;
            }
        }
        // 四个为一组(最小单位输出)
       if(i==2){
           offset += sprintf(out+offset,"%s","元");
           if(num[i]!=0)
               offset += sprintf(out+offset,"%s",up_digit[num[i]-1]);
           continue;
        }
        else if(i==6){
            offset += sprintf(out+offset,"%s","万");
            if(num[i]!=0)
                offset += sprintf(out+offset,"%s",up_digit[num[i]-1]);
            continue;
        }
        else if(i==10){
            offset += sprintf(out+offset,"%s","亿");
            if(num[i]!=0)
                offset += sprintf(out+offset,"%s",up_digit[num[i]-1]);
            continue;
        }
        // 其他位处理
        if(num[i]==0){       // 先处理该位为0的情况
            if(num[i-1]!=0){ // 非连续零则加零
                offset += sprintf(out+offset,"%s","零");
                continue;
            }
            else{
                continue;
            }
        }
        else{
            if((i==3||i==7||i==11)&&num[i]==1){ // 每一组上的拾位单独处理
                offset += sprintf(out+offset,"%s","拾");
            }
            else{
                offset += sprintf(out+offset,"%s",up_unit[13-i]);
                offset += sprintf(out+offset,"%s",up_digit[num[i]-1]);
            }
        }
    }
    offset+=sprintf(out+offset,"%s","币民人");
    char out1[100] = {0};
    int k = 0;
    for(int i=offset-1;i>=0;i-=3){ // 逆序输出--注意三个字节装一个汉字
        out1[k+2] = out[i];
        out1[k+1] = out[i-1];
        out1[k] = out[i-2];
        k+=3;
    }
    printf("%s",out1);
    return 0;     
 
    
}


全部评论
代码没认真看,但是用浙大那位经常出现的大佬给的用例运行输出错误,只有万位为零时万位照样输出万字
点赞 回复 分享
发布于 2022-07-20 20:06

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务