zoukankan      html  css  js  c++  java
  • STL :sscanf sprintf的应用

    PAT 1054

     网上看到的,很好的应用了这两个函数。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    #include <bits/stdc++.h>
    using namespace std;
    int main() {
        int n, cnt = 0;
        char a[50], b[50];
        double temp, sum = 0.0;
        cin >> n;
        for(int i = 0; i < n; i++) {
            scanf("%s", a);
            sscanf(a, "%lf", &temp);  //从一个字符串中读进与指定格式相符的数据
            sprintf(b, "%.2lf",temp); //字符串格式化命令,主要功能是把格式化的数据写入某个字符串中
            int flag = 0;
            for(int j = 0; j < strlen(a); j++) {
                if(a[j] != b[j]) {
                    flag = 1;
                }
            }
            if(flag || temp < -1000 || temp > 1000) {
                printf("ERROR: %s is not a legal number ", a);
                continue;
            else {
                sum += temp;
                cnt++;
            }
        }
        if(cnt == 1) {
            printf("The average of 1 number is %.2lf", sum);
        else if(cnt > 1) {
            printf("The average of %d numbers is %.2lf", cnt, sum / cnt);
        else {
            printf("The average of 0 numbers is Undefined");
        }
        return 0;
    }
  • 相关阅读:
    sql server 数据查询基础
    sqlserver 用SQL语句操作数据
    sql server 用表组织数据
    sql server 程序的集散地 数据库
    JAVA 面向对象 File I/O
    JAVA 面向对象 多线程
    JAVA 面向对象 集合框架
    JAVA 面向对象 异常
    js内置对象、定时函数、document对象
    DOM
  • 原文地址:https://www.cnblogs.com/bestwzh/p/6492848.html
Copyright © 2011-2022 走看看