主要还是两个函数的使用:sscanf 和 sprintf
sscanf
int sscanf(const char * s,const char * format,...);
sprintf
int sprintf(char * str,const char * format,...);
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 5 int main() { 6 int n = 0, k = 0; 7 float sum = 0; 8 cin >> n; 9 for (int i = 0; i < n; ++i) { 10 char s1[100], s2[100]; //一定要定义足够大,否则会出现测试点2运行时错误 11 float num = 0.0; 12 cin >> s1; 13 sscanf(s1, "%f", &num); //将s1中浮点数写入num 14 sprintf(s2, "%.2f", num); //num保留两位数字输出到s2 15 if (strncmp(s1, s2, strlen(s1)) == 0 && (num <= 1000 && num >= -1000)) { //利用strncmp,防止读取s2中多余的0 16 sum += num; 17 k++; 18 } 19 else { 20 cout << "ERROR: " << s1 << " is not a legal number" << endl; 21 } 22 } 23 if (k == 0) cout << "The average of 0 numbers is Undefined"; 24 else if (k == 1) printf("The average of 1 number is %.2f", sum / k); //注意只有一个数字的情况 25 else printf("The average of %d numbers is %.2f", k, sum / k); 26 return 0; 27 }