(1)题意:有多组数组,以键入结束为结束,本来一个代码,循环来写一定不会出错,但是如果用数学公式来的话不小心就会出错,(n+1)*n/2肯定不会超过32位有符号位,但是,(n+1)*n就不一定了。所以以后做题目,在WA的时候测试数据的时候可以选择边缘数据来测试。注意数据范围。
(2)代码1:
#include<iostream>
using namespace std;
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int n;
while(cin>>n){
if(n%2==0)cout<<n/2*(n+1)<<endl<<endl;
else cout<<(n+1)/2*n<<endl<<endl;
}
}
(3)代码2:
#include<iostream>
using namespace std;
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int n;
while(cin>>n){
int sum=0;
for(int i=1;i<=n;i++)sum+=i;
cout<<sum<<endl;
}
}
本文探讨了使用数学公式处理数组求和的问题,特别是针对可能导致整数溢出的情况。通过两个示例代码展示了如何避免此类错误,并强调了在编写算法时考虑数据范围的重要性。
993

被折叠的 条评论
为什么被折叠?



