Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 第一个代码错误,但第二个代码正确“;在抛出';std::bad#u alloc';what();_C++ - Fatal编程技术网

C++ 第一个代码错误,但第二个代码正确“;在抛出';std::bad#u alloc';what();

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>

我的代码在第一个代码中给出了错误,但第二个代码运行时没有任何错误“在抛出'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)
{
    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;
}