PAT B1054 Averaging (20 points) (Analysis of test points 0, 1, 2, 3)

Insert picture description here
Very disgusting string simulation questions, mainly because the test points are disgusting.
Test point 0: the case of the sample, the sample can pass this
test point 1: the case of the divisor is 0, the output is judged specifically.
Test point 2: the divisor is singular, and the output "The average of 1 number is Y", pay attention There is no s after the number! ! !
Test point 3: The most disgusting test point, because the number in the form of "123." with the decimal point at the last digit is also counted as a legal number. The question is not clearly stated. I always thought that the decimal point at the end is also illegal. I've been looking for TvT for a long time

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>

using namespace std;

bool isclegal(char c){
    
    
	if(!(c>='0'&&c<='9') && c!='-' && c!='.') return false;
	return true;
}

bool isslegal(string s){
    
    
	int dian = 0;
	int pd;
	bool havenum = false;
	for(int i=0; i<s.size(); i++){
    
    
		if(!isclegal(s[i])){
    
    
			return false;
		}else{
    
    
			if(s[i] == '-'){
    
    
				if(i != 0) return false;
			}
			if(s[i] == '.'){
    
    
				if(i==0) return false;
				pd = i;
				dian++;
			} 
			if(dian > 1) return false;
			if(s[i]<='9' && s[i]>='0') havenum = true;
		}
	}
	if(!havenum) return false;
	if(dian == 1){
    
    
		int len = s.size() - pd - 1;
		if(len > 2) return false;
	}
	double d = stof(s);
	if(d<-1000 || d>1000) return false;
	
	return true;
}

int main(){
    
    
	int n;
	double sum = 0;
	int num = 0;
	scanf("%d", &n);
	
	string str[n];
	for(int i=0; i<n; i++){
    
    
		cin >> str[i];
		if(isslegal(str[i])){
    
    
			sum += stof(str[i]);
			num++;
		}else{
    
    
			printf("ERROR: %s is not a legal number\n", str[i].c_str());		
		}
	}
	if(num == 0){
    
    
		printf("The average of 0 numbers is Undefined");
	}else if(num == 1){
    
    
		printf("The average of 1 number is %.2f", num, sum/(num*1.0));
	}else{
    
    
		printf("The average of %d numbers is %.2f", num, sum/(num*1.0));
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45964844/article/details/113681652