题目:https://pintia.cn/problem-sets/994805260223102976/problems/994805272659214336
参考:https://www.liuchuo.net/archives/617

注意点

这题主要利用了sscanf和sprintf,如下

  1. sscanf(a, "%lf", &temp);//把a输入进temp中
  2. sprintf(b, "%.2f", temp);//把temp的东西打印到b里

代码

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstring>
  4. using namespace std;
  5. int main(){
  6. int n, cnt = 0;
  7. char a[50], b[50];
  8. double temp, sum = 0.0;
  9. cin >> n;
  10. for(int i = 0; i < n; i++){
  11. scanf("%s", a);
  12. sscanf(a, "%lf", &temp);
  13. sprintf(b, "%.2f", temp);
  14. int flag = 0;
  15. for(int j = 0; j < strlen(a); j++)
  16. if(a[j] != b[j]) flag = 1;
  17. if(flag || temp < -1000 || temp > 1000){
  18. printf("ERROR: %s is not a legal number\n", a);
  19. continue;
  20. } else {
  21. sum += temp;
  22. cnt++;
  23. }
  24. }
  25. if(cnt == 1){
  26. printf("The average of 1 number is %.2f", sum);
  27. } else if(cnt > 1)
  28. printf("The average of %d numbers is %.2f", cnt, sum / cnt);
  29. else
  30. printf("The average of 0 numbers is Undefined");
  31. return 0;
  32. }