学习C++时出现警告C26451:算术溢出

警告        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);
}

 

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值