sscanf() – 从一个字符串中读进与指定格式相符的数据
sprintf() – 字符串格式化命令,主要功能是把格式化的数据写入某个字符串中。
真好
#include<iostream> #include<cstdio> #include<string.h> using namespace std; int main(){ int n,cnt=0; double tmp,sum=0.0; char a[50],b[50]; cin>>n; for(int i=0;i<n;i++){ scanf("%s",a); sscanf(a,"%lf",&tmp); sprintf(b,"%.2f",tmp); int flag=0; for(int j=0;j<strlen(a);j++){ // cout<<"a[j]="<<a[j]<<" b[j]="<<b[j]<<endl; if(a[j]!=b[j]){ flag=1; break; } } if(flag||tmp<-1000||tmp>1000){ printf("ERROR: %s is not a legal number\n", a); continue; }else { sum+=tmp; cnt++; } } if(cnt==1) printf("The average of 1 number is %.2f", sum); else if(cnt > 1) printf("The average of %d numbers is %.2f", cnt, sum / cnt); else printf("The average of 0 numbers is Undefined"); return 0; }
原文地址:https://www.cnblogs.com/xx123/p/10354654.html
时间: 2024-11-10 10:53:11