C++ 第一个代码错误,但第二个代码正确“;在抛出';std::bad#u alloc';what();
我的代码在第一个代码中给出了错误,但第二个代码运行时没有任何错误“在抛出'std::bad_alloc'实例后终止调用what():std::bad_alloc中止(内核转储)” //首先C++ 第一个代码错误,但第二个代码正确“;在抛出';std::bad#u alloc';what();,c++,C++,我的代码在第一个代码中给出了错误,但第二个代码运行时没有任何错误“在抛出'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>
#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)
{
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\u alloc
的原因
第二个版本工作得很好,因为在除以26之前先减去1,这意味着当循环以
n=0
开始时会有一个点,如果n=n/26
曾经等于0呢?在第一种情况下,n-=1
将产生一个负值。无关:避免使用位
中的任何include。它们是仅供库实现使用的内部标头。这个特殊的头文件stdc++.h可能是一个特别糟糕的禁忌。这里有更多关于它的信息:
while(n)
{
res.push_back((n%26) + 'A');
n=n/26;
n-=1;
}