警告 C26451 算术溢出: 使用 4 字节值上的运算符 - ,然后将结果转换到 8 字节值。在调用运算符 - 之前将值强制转换为宽类型可避免溢出(io.2)。
代码中的 long int size = n - 1;
cout << numVec.at(size);// 没有警告!
但改成 cout<<numVec.at(static_cast<long int>(n-1)); //出现上述警告! 请问下这是什么原因。
#include<iostream>
#include<list>
#include<vector>
#include<string>
#include<sstream>
using std::string;
using std::stringstream;
using std::cin;
using std::cout;
using std::endl;
using std::list;
using std::vector;
using std::iterator;
list<double> numList;
vector<double> numVec;
double standard_deviation(int n,double average);
int main() {
string input_str;
cout << "请输入一系列数字: ";
getline(cin, input_str);
//16.3防止输入为空的错误!
if (input_str.size()==0) {
cout << "列表为空!"<<endl;
system("PAUSE");
return -1;
}
stringstream ss(input_str);
double x = 0.0;
double sum = 0.0;
while (ss >> x) {
numList.push_back(x);
sum += x;
}
numList.sort();
long int n = static_cast<long int>(numList.size());
numVec.assign(numList.begin(), numList.end());
int n1 = n / 2;
int n2 = (n - 1) / 2;
cout << "这一系列数字的平均值是:";
cout << sum / n << endl;
cout << "这一系列数字的的最小值是:";
cout << numVec.at(0) << endl;
cout << "这一系列数字的最大值是:";
long int size = n - 1;
cout << numVec.at(size);
cout<< endl;
cout << "这一系列数字的中位数为:";
cout << (numVec.at(n1) + numVec.at(n2)) / 2;
cout << endl;
cout << "这一系列数字的标准差是:";
cout<< standard_deviation(n, sum / n) << endl;
cout << "请输入回车退出";
cin.ignore();
return 0;
}
double standard_deviation(int n,double average) {
vector<double>::iterator it = numVec.begin();
double S = 0.0;
while (it!=numVec.end()){
S = S + (*it - average) * (*it - average);
++it;
}
return sqrt(S / n);
}