1108 Finding Average

#include<iostream>

#include<string>

#include<cstring> // strlen()

#include<cstdio>

#include<iomanip>

using namespace std;

int main(){

int n, cnt = 0;

char a50, b50;

cin >> n;

double tmp = 0.0, sum = 0.0;

for(int i = 0; i < n; i++){

cin >> a;

// 使用sscanf将字符串转换为double形式

if(sscanf(a, "%lf", &tmp) != 1){

cout << "ERROR: " << a << " is not a legal number" << endl;

continue;

}

// 使用sprintf将tmp格式转换为两位小数

sprintf(b, "%.2f", tmp);

int flag = 0;

int len = strlen(a);

// 检查原始字符串和格式化后的字符串是否一致

for(int j = 0; j < len; j++){

if(aj != bj){

flag = 1;

break;

}

}

// 如果格式不一致或超出范围

if(flag != 0 || tmp < -1000 || tmp > 1000){

cout << "ERROR: " << a << " is not a legal number" << endl;

continue;

} else {

sum += tmp;

cnt++;

}

}

// 输出结果

if(cnt == 0){

cout << "The average of 0 numbers is Undefined" << endl;

} else if(cnt == 1){

cout << "The average of 1 number is "

<< fixed << setprecision(2) << sum << endl;

} else {

cout << "The average of " << cnt << " numbers is "

<< fixed << setprecision(2) << sum / cnt << endl;

}

return 0;

}

相关推荐
A加ITIL教练长河achotsao1 小时前
ITIL Master 战略领导者课后系列分享:AI编程正在重新划分研发与运维的边界
算法
hahaha60161 小时前
FPGA+ARM实现AWB的全流程
人工智能·嵌入式硬件·算法·计算机视觉·fpga开发
李洱1 小时前
LangChain 和 LangGraph 的区别:核心原理与使用场景
算法
夏幻灵1 小时前
每日一题:LeetCode 206:反转链表——三指针与原地反转详解
算法·leetcode·链表
神仙别闹1 小时前
基于C++实现的贪吃蛇游戏平台
java·c++·游戏
CQU_JIAKE1 小时前
10.9【A】
数据结构
第25小时记录1 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·python
王老师青少年编程2 小时前
2026年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
C++ 老炮儿的技术栈2 小时前
static的作用
c语言·c++·人工智能·单片机·c