PAT Basic Level 1054 求平均值 (20 分)

题目链接:

https://pintia.cn/problem-sets/994805260223102976/problems/994805272659214336

AC代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cctype>

using namespace std;
int n;
char str[101][101];
bool check(char s[]){
    int i=0;
    if(s[0]=='-')
        i++;
    for(;s[i]&&s[i]!='.';i++){
        if(!isdigit(s[i])){
            return false;
        }
    }
    if(s[i]=='.'){
        for(int j=i+1;s[j];j++){
            if(!isdigit(s[j])||j-i>2){
            //判断是否是数字
            //并且最多精确到小数点后 2 位
                return false;
            }
        }
    }
    double a=fabs(atof(s));
    if(a>1000.0)
    {
        return false;
    }
    return true;
}

void solve(){
    int ans=0;//合法输入的个数
    double sum=0;//合法输入的数字之和
    for(int i=0;i<n;i++){
        if(check(str[i]))
        {
            ans++;
            sum+=atof(str[i]);
        }
        else{
            printf("ERROR: %s is not a legal number\n",str[i]);
        }
    }
    if(ans){
        if(ans==1){
            printf("The average of 1 number is %.2lf\n",sum);
        }
        else{
            printf("The average of %d numbers is %.2f\n",ans,sum/ans);
        }
    }
    else{
        printf("The average of 0 numbers is Undefined\n");
    }
}

int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%s",str[i]);
    }
    solve();
    return 0;
}

二刷 :


#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	int T;
	cin >> T;
	char a[50],b[50];
	double temp,sum=0;
	int count=0;

	while(T--)
	{
		scanf("%s",a);
		sscanf(a,"%lf",&temp);//将a字符串转换为格式lf存到temp里 
		//cout << temp << endl;
		sprintf(b, "%.2lf",temp);//将格式化的temp写入字符串b 
		int flag = 0;
		for(int j=0;j<strlen(a);j++)//判断新的字符串跟原来的是不是相等的 
		{
			if(a[j]!=b[j])
				flag = 1;
		}

		if(flag || temp<-1000||temp>1000)//如果flag = 1表示不相等有问题 
		{
			printf("ERROR: %s is not a legal number\n",a);
		}
		else
		{
			count++;
			sum += temp; 
		} 


	}
//	cout  << sum << " " << count << " " <<sum/count<< endl;
	if(count==1)
	{
		printf("The average of 1 number is %.2lf\n",sum);
	} 
	else if(count > 1)
	{
		printf("The average of %d numbers is %.2lf\n",count,(double)sum/count); 
	} 

	else
	{
		printf("The average of 0 numbers is Undefined\n");
	}
	return 0;

 } 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值