码迷,mamicode.com
首页 > 其他好文 > 详细

【OI】计算分子量 Molar mass UVa 1586 题解

时间:2019-07-25 00:21:51      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:说明   溢出   main   没有   注释   直接   scanf   const   数字   

题目:(由于UVa注册不了,还是用vjudge)

https://vjudge.net/problem/UVA-1586

技术图片

详细说明放在了注释里面。原创。

破题点在于对于一个元素的组合(元素+个数),只有3种可能:

1、单个元素

2、一个元素和一位数字

3、一个元素和两位数字

没有了。因为题设交代了n<=99,表明个数只能为2位数。分别判断即可。

/*
Copyright 2019 AlexanderZ.Tang
Molar_mass.cpp
For UVa 1586
https://cnblogs.cn/nowonder
*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>

const int num[] = {0,1,2,3,4,5,6,7,8,9};    //使用数组将字符数字转为数字,ch - ‘0‘即为该数字的下标 
char s[80];        //储存字符串,n<=80 

double get_mass(char ch)
{
    //获得对应字符的分子量 
    
    if (ch==C)    return 12.01;
    if (ch==H)    return 1.008;
    if (ch==O)    return 16.00;
    if (ch==N)    return 14.01;
}

int main()
{
    int T;
    double sum;
    scanf("%d",&T);
    while (T--)    //计数器 
    {
        sum = 0;
        scanf("%s",s);
        int len = strlen(s);
        if (len < 2)    //对于单个字符,直接输出,否则造成溢出  
        {
            printf("%.3lf\n",get_mass(s[0]));
            continue;
        }
        
        for (int i=0;i<len-2;i++)    //防止溢出,从0到len-3 
        {
            if (!isalpha(s[i]))    continue;    //数字跳过 
            
            if (!isalpha(s[i+1]))    //一个元素带一个数字(个位数) 
            {
                if (!isalpha(s[i+2]))    //一个元素带两个数字(十位数) 
                {
                    sum += get_mass(s[i]) * (num[s[i+1] - 0] * 10 + num[s[i+2] - 0]);    
                }
                else
                {
                    sum += get_mass(s[i]) * num[s[i+1] - 0];
                }
            }
            else    //单独元素,直接算 
            {
                sum += get_mass(s[i]);
            }
        }
        
        //字符串s中剩下两个字符
        //如果全是数字直接跳
         
        if (isalpha(s[len-2]))     
        {
            if (!isalpha(s[len-1]))    //元素带个位数 
            {
                sum += get_mass(s[len-2]) * num[s[len-1] - 0];
            }
            else    //单独元素 
            {
                sum += get_mass(s[len-2]);
            }
        }

        if (isalpha(s[len-1]))    sum += get_mass(s[len-1]);    //最后一个字符 
        printf("%.3lf\n",sum);    //输出 
    }
    return 0;
}

 

【OI】计算分子量 Molar mass UVa 1586 题解

标签:说明   溢出   main   没有   注释   直接   scanf   const   数字   

原文地址:https://www.cnblogs.com/nowonder/p/Molar_mass.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!