题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805360777347072
基本一遍过,题意理解有点问题
注意count = 1时,输出的是number

代码

  1. #include <cstdio>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. bool judge(string str){
  6. int dotcount = 0;
  7. for(int i = 0; i < str.size(); i++){
  8. if(!((str[i] >= '0' && str[i] <= '9')|| str[i] == '.' || str[i] == '-')){
  9. return false;
  10. }
  11. else if(str[i] == '.'){
  12. if(str.size() - i > 3) return false;
  13. dotcount++;
  14. if(dotcount > 1) return false;
  15. }
  16. }
  17. if(stod(str) > 1000.0 || stod(str) < -1000.0) return false;
  18. return true;
  19. }
  20. int main(){
  21. int n, count = 0;
  22. double sum = 0.0;
  23. string input;
  24. scanf("%d", &n);
  25. for(int i = 0; i < n; i++){
  26. cin>>input;
  27. if(judge(input)){
  28. count++;
  29. sum += stod(input);
  30. } else {
  31. cout<<"ERROR: "<<input<<" is not a legal number"<<endl;
  32. }
  33. }
  34. if(count == 0){
  35. printf("The average of 0 numbers is Undefined");
  36. } else if(count == 1){
  37. printf("The average of 1 number is %.2f", sum/count);
  38. }
  39. else {
  40. printf("The average of %d numbers is %.2f", count, sum/count);
  41. }
  42. return 0;
  43. }