• PAT 甲级 1108 Finding Average (20 分)


    思路:

    1.不是数字的位置只能在第一个且为负号,或者在字符串的倒数第一、二、三位置、或者不存在;
    2.上面的方法也可以用sscanf或者sprintf进行判定;
    3.数字要在规定区间内;
    4.按.2f输出就好了;

    代码:

    #include<iostream>
    #include<string>
    #include<cctype>
    using namespace std;
    bool isLegal(string s){
    	int pos=s.find('.'),len=s.length();
    	if(pos==len-1||pos==len-2||pos==len-3||pos==string::npos){
    		for(int i=0;i<len;i++)
    			if(!isdigit(s[i])&&i!=pos&&(i||s[i]!='-')) return false;
    		double n=stod(s);
    		if(n>1000||n<-1000) return false;
    		return true;
    	}
    	return false;
    }
    int main(){
    	int n,cnt=0;
    	double sum=0;
    	cin>>n;
    	for(int i=0;i<n;i++){
    		string s;
    		cin>>s;
    		if(!isLegal(s)) printf("ERROR: %s is not a legal number
    ",s.c_str());
    		else{
    			sum+=stod(s);
    			cnt++;
    		}
    	}
    	if(cnt>1) printf("The average of %d numbers is %.2f",cnt,sum/(cnt*1.0));
    	else if(cnt==1) printf("The average of 1 number is %.2f",sum);
    	else printf("The average of 0 numbers is Undefined");
    	return 0;
    }
    
  • 相关阅读:
    Login02
    工作笔记
    vim 使用笔记
    linux 命令常用笔记
    百度面试测试开发工程师内容
    sublime 快捷键
    如何升级php版本---从php5.5.12 升级php7.1.5 wamp实践
    如何新建自己的服务
    php.ini 文件中配置的意义注释
    linux 如何打包代码
  • 原文地址:https://www.cnblogs.com/yuhan-blog/p/12309010.html
Copyright © 2020-2023  润新知