使用cout输出小数点后指定位数用cout << setiosflags(ios::fixed)<< setprecision(2) << a << endl;
当然也可以使用printf("%.2f", a);
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
bool islegal(string str)
{
int cnt = 0;
for(int i = 0; i < str.size(); i++)
{
if(isalpha(str[i]))
return false;
if(str[i] == '.')
{
cnt++;
//小数点后的位数大于2
string tmp = str.substr(i+1);
if(tmp.size() > 2)
return false;
if(cnt >= 2)
return false;
}
}
double tmp = stod(str);
if(tmp < -1000 || tmp > 1000)
return false;
return true;
}
int main()
{
int n;
string str;
while(cin >> n)
{
getchar();
getline(cin, str);
int j = 0, cnt = 0;
double sum = 0;
for(int i = 0; i < str.size(); i++)
{
if(str[i] == ' ' || i == str.size()-1)
{
//如果是最后一个字符,要将i++,这样才能截取到完整的最后一个单词
if(i == str.size()-1)
i++;
if(islegal(str.substr(j, i-j)))
{
double tmp = stod(str.substr(j, i-j));
sum += tmp;
cnt++;
}
else
cout << "ERROR: " << str.substr(j, i-j) <<" is not a legal number" << endl;
j = i+1; //下一个单词开始的地方
}
}
if(cnt > 1)
cout << "The average of " << cnt <<" numbers is " <<setiosflags(ios::fixed)<<setprecision(2) << sum/cnt << endl;
else if(cnt == 1)
cout << "The average of 1 number is " << setiosflags(ios::fixed)<<setprecision(2) << sum << endl;
else
cout << "The average of 0 numbers is Undefined" << endl;
}
return 0;
}