![](/img/trans.png)
[英]I get the error which i cant fix : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped)
[英]error in 1st code but 2nd one correct “terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted(core dumped)”
我的代碼在第一個代碼中給出了錯誤,但是第二個代碼正在運行而沒有任何錯誤“在拋出'std :: bad_alloc'what()實例之后終止調用:std :: bad_alloc中止(轉儲內核)” //第一個
#include<bits/stdc++.h>
using namespace std;
int main()
{
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string res;
while(n)
{
res.push_back((n%26) + 'A');
n=n/26;
n-=1;
}
reverse(res.begin(),res.end());
cout<<res<<endl;
}
return 0;
}
第二個代碼如下所示,沒有錯誤,任何人都可以告訴我為什么出現此錯誤
while(n)
{
n-=1;
res.push_back((n%26) + 'A');
n=n/26;
}
第一個示例中的問題是
while(n)
{
res.push_back((n%26) + 'A');
n=n/26;
n-=1;
}
將成為無限循環。 為什么? 因為n/26
是整數除法。 這意味着,當n < 26 && n > -26
,除法將返回0。在循環末尾減去1時,將發生的情況是n始終為-1: -1/26 = 0
和0 - 1 = -1
。 因此,您的字符串將變得太大,這就是導致std::bad_alloc
。
第二個版本工作得很好,因為在除以26之前先減去一個,這意味着當循環以n=0
開頭時會有一點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.