C++ 在线编译器在c+;中使用字符串时出现运行时错误+;
我试图在在线编译器上运行这段代码,它在本地完美运行的同时显示运行时错误。未使用的代码部分已注释掉C++ 在线编译器在c+;中使用字符串时出现运行时错误+;,c++,runtime-error,c++14,C++,Runtime Error,C++14,我试图在在线编译器上运行这段代码,它在本地完美运行的同时显示运行时错误。未使用的代码部分已注释掉 #include <iostream> #include <string> #include <cmath> using namespace std; int main() { // your code goes here ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
// your code goes here
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
int x,y;
cin>>x>>y;
string ans;
int noOfApple=0,noOfBanana=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='a')
{
noOfApple++;
}
else
{
noOfBanana++;
}
}
int noOfABlock=ceil(noOfApple/x);
//int noOfBBlock=ceil(noOfBanana/y);
int length=floor(noOfBanana/(noOfABlock-1));
int remainderB=noOfBanana%(noOfABlock-1);
int counter=0;
//condition for '*'
if(noOfBanana<(noOfABlock-1))
{
int q=noOfBanana;
for(int i=0;i<(noOfABlock-1);i++)
{
for(int j=0;j<x;j++)
{
ans[counter++]='a';
}
if(q>0)
{
ans[counter++]='b';
q--;
}
else
{
ans[counter++]='*';
}
}
for(int i=0;i<x;i++)
{
ans[counter++]='a';
}
}
else{
for(int i =0;i<(noOfABlock-1);i++)
{
for(int j=0;j<x;j++)
{
ans[counter++]='a';
}
for(int j=0;j<length;j++)
{
ans[counter++]='b';
}
while(remainderB>0)
{
remainderB--;
ans[counter++]='b';
}
}
for(int i=0;i<x;i++)
{
ans[counter++]='a';
}
}
cout<<ans<<endl;
}
return 0;
}
当使用数组时,我们必须初始化数组的大小,因为它们是静态的,但字符串是动态的,我们不需要使用大小进行初始化。您给它什么输入?想想如果
noofblock
或noofblock
是1
,会发生什么情况。不要使用0
而不是false
,这会使您的代码混乱。同样,不要使用0
(或其宏NULL
)而不是nullptr
,因为您使用的是C++14。没有使用noobblock
,因此也没有真正使用y
。如果您不使用它们,只需从程序中删除它们。当我使用您的输入示例运行它时,我在表达式noOfBanana/(noOfABlock-1)
处得到一个零除异常。我还得到了三个编译器警告,它们很容易修复,可能不会导致运行时错误。您应该提供关于运行时错误的所有信息。
6
ab
1 1
aab
1 1
aabb
1 2
aaaaab
2 1
aaaa
1 3
aaaaa
2 2