molsonsama @ 2024-02-01 15:44:53
代码如下,hack那一项很奇怪 具体错误信息为
“Wrong Answer.wrong answer On line 1 column1,read 2, expected 1.”
但是在本地运行数据的时候,结果是正确的。 输入: 0 1 输出: 1
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream answer;
int n;
cin >> n;
int index[n] = {0};
for (int i = n; i >= 0; i--)
{
cin >> index[i];
}
if (n > 1){
if (index[n] == 1)
{
answer << "x^" << n;
}
else if (index[n] == -1)
{
answer << "-x^" << n;
}
else if (index[n] != 0)
{
answer << index[n] << "x^" << n;
}
}
for (int i = n - 1; i > 1; i--)
{
if (index[i] == 0)
{
continue;
}
else if (index[i] == 1)
{
answer << "+x^" << i;
}
else if (index[i] == -1)
{
answer << "-x^" << i;
}
else if (index[i] > 0)
{
answer << "+" << index[i] << "x^" << i;
}
else if (index[i] < 0)
{
answer << index[i] << "x^" << i;
}
}
if (index[1] != 0)
{
if (index[1] > 1)
answer << "+" << index[1] << "x";
else if (index[1] < -1)
answer << index[1] << "x";
else if (index[1] == 1)
answer << "+x";
else if (index[1] == -1)
answer << "-x";
}
if (index[0] != 0)
{
if (index[0] > 0)
answer << "+" << index[0] << endl;
else
answer << index[0] << endl;
}
string ans = answer.str();
if (ans[0] == '+')
ans.erase(ans.begin());
if(ans == "") cout << 0;
cout << ans << endl;
return 0;
}
by molsonsama @ 2024-02-01 15:45:31
求助,谢谢了
by ilibilib @ 2024-02-01 15:52:59
@molsonsama
#include <iostream>
#include <sstream>
using namespace std;
int index[100] = {0};
int main()
{
stringstream answer;
int n;
cin >> n;
for (int i = n; i >= 0; i--)
{
cin >> index[i];
}
if (n > 1){
if (index[n] == 1)
{
answer << "x^" << n;
}
else if (index[n] == -1)
{
answer << "-x^" << n;
}
else if (index[n] != 0)
{
answer << index[n] << "x^" << n;
}
}
for (int i = n - 1; i > 1; i--)
{
if (index[i] == 0)
{
continue;
}
else if (index[i] == 1)
{
answer << "+x^" << i;
}
else if (index[i] == -1)
{
answer << "-x^" << i;
}
else if (index[i] > 0)
{
answer << "+" << index[i] << "x^" << i;
}
else if (index[i] < 0)
{
answer << index[i] << "x^" << i;
}
}
if (index[1] != 0)
{
if (index[1] > 1)
answer << "+" << index[1] << "x";
else if (index[1] < -1)
answer << index[1] << "x";
else if (index[1] == 1)
answer << "+x";
else if (index[1] == -1)
answer << "-x";
}
if (index[0] != 0)
{
if (index[0] > 0)
answer << "+" << index[0] << endl;
else
answer << index[0] << endl;
}
string ans = answer.str();
if (ans[0] == '+')
ans.erase(ans.begin());
if(ans == "") cout << 0;
cout << ans << endl;
return 0;
}
数组开在外面
by molsonsama @ 2024-02-01 19:45:00
@ilibilib 谢谢!但是请问为什么数组在里面会导致结果错误呢?
by ilibilib @ 2024-02-01 20:02:18
@molsonsama 大概是数组是静态的,程序执行之前就要根据开的数组大小分配内存,所以数组大小必须是确定的数字,而不是在程序执行之后才决定数组大小。除非你用动态数组。
(?我不知道说得准不准确,反正差不多是这样的
by molsonsama @ 2024-02-01 20:19:20
@ilibilib 好的,谢谢!