zoukankan      html  css  js  c++  java
  • PTA 乙级 1054 求平均值 (20分) C/C++

     主要还是两个函数的使用:sscanf 和 sprintf

    sscanf

     int sscanf(const char * s,const char * format,...); 

    sprintf

     int sprintf(char * str,const char * format,...); 

     1 #include<iostream>
     2 #include<cstring>
     3 using namespace std;
     4 
     5 int main() {
     6     int n = 0, k = 0;
     7     float sum = 0;
     8     cin >> n;
     9     for (int i = 0; i < n; ++i) {
    10         char s1[100], s2[100];                    //一定要定义足够大,否则会出现测试点2运行时错误
    11         float num = 0.0;
    12         cin >> s1;
    13         sscanf(s1, "%f", &num);                    //将s1中浮点数写入num
    14         sprintf(s2, "%.2f", num);                //num保留两位数字输出到s2
    15         if (strncmp(s1, s2, strlen(s1)) == 0 && (num <= 1000 && num >= -1000)) {    //利用strncmp,防止读取s2中多余的0
    16             sum += num;
    17             k++;
    18         }
    19         else {
    20             cout << "ERROR: " << s1 << " is not a legal number" << endl;
    21         }
    22     }
    23     if (k == 0) cout << "The average of 0 numbers is Undefined";
    24     else if (k == 1) printf("The average of 1 number is %.2f", sum / k);    //注意只有一个数字的情况
    25     else printf("The average of %d numbers is %.2f", k, sum / k);
    26     return 0;
    27 }

           

    默默地一点点变强,细节决定成败
  • 相关阅读:
    正则表达式 1
    14 同步 1
    14 线程属性
    14 线程状态
    14 线程
    window.location.hostname与 window.location.host 区别
    泛型 的通配符类型 extends super
    svn拷贝一个项目作为新项目
    List Collections sort
    && 和 || 逻辑运算符
  • 原文地址:https://www.cnblogs.com/SCP-514/p/13538885.html
Copyright © 2011-2022 走看看