zoukankan      html  css  js  c++  java
  • 【算法笔记】B1054 求平均值

    atof(str)字符串转换浮点数
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 bool isLegal(char *s){
     4     int i = 0;
     5     if(s[0]=='-'){
     6         i++;
     7     }
     8     for(;s[i]&&s[i]!='.';i++){
     9         if(!isdigit(s[i])){
    10             return false;
    11         }
    12     }
    13     if(s[i]=='.'){
    14         for(int j=i+1;s[j];j++){
    15             if(!isdigit(s[j])||j-i>2){
    16                 return false;
    17             }
    18         }
    19     }
    20     double a = fabs(atof(s));
    21     if(a>1000.0){
    22         return false;
    23     }
    24     return true;
    25 }
    26 int main(){
    27     int n,nums = 0;
    28     double sum;
    29     char *x;
    30     x=(char *)malloc(sizeof(char));
    31     cin>>n;
    32     for(int i = 0; i < n; i++){
    33         scanf("%s", x);
    34         if(isLegal(x)){
    35             nums++;
    36             sum += atof(x);
    37         }else{
    38             printf("ERROR: %s is not a legal number
    ", x);
    39         }    
    40     }
    41     if(nums){
    42         if(nums==1){
    43             printf("The average of 1 number is %.2lf
    ",sum);
    44         }else{
    45             printf("The average of %d numbers is %.2lf
    ",nums,sum/nums);
    46         }
    47     }else{
    48         printf("The average of 0 numbers is Undefined
    ");
    49     }
    50     return 0;
    51 }
  • 相关阅读:
    mongodb 记录
    php保存文件
    调用AngularJS的API
    angular修改数据
    大小写转换
    使用Properties类动态加载配置文件里的内容
    org.apache.commons.cli.Options
    Google guava和Apache commons
    orc格式文件
    shell的awk命令使用
  • 原文地址:https://www.cnblogs.com/chunlinn/p/10799383.html
Copyright © 2011-2022 走看看