[英]I don't know how to fix my code , it doesn't work properly
我有一个关于 c++ 的问题和一个我必须解决的问题。 实际上,我写了一段代码,但在线评委给了我 100 分中的 70 分,并说我的代码在 3 个测试用例中无法正常工作。 我找不到错误来纠正它,如果有人可以帮助我,我将不胜感激。 谢谢
我想为每 2 个自然数 a, b 打印输出,它们构成 a/b 分数。 例如,对于数字 (2),它应该在输出中打印 1 1,因为我们不考虑 (0,0) 并且我们在螺旋路径上的坐标中到达的第二个点是 (1,1)。 输入应该是自然数,输出应该是纵横坐标。
例如,输入是 12,其输出是 2 2。更多信息在这些照片中:
#include<iostream>
using namespace std;
int main()
{
int i,j,x,y,count;
unsigned int n;
x=0;
y=0;
count=0;
cin>>n;
for(i=1;i<=30000;i++)
{
if(i%2!=0)
{
for(j=0;j<i;j++)
{
x++;
count++;
if(count==n)
{
cout<<x<<" "<<y;
}
}
for(j=0;j<i;j++)
{
y++;
count++;
if(count==n)
{
cout<<x<<" "<<y;
}
}
}
else
if(i%2==0)
{
for(j=0;j<i;j++)
{
x--;
count++;
if(count==n)
{
cout<<x<<" "<<y;
}
}
for(j=0;j<i;j++)
{
y--;
count++;
if(count==n)
{
cout<<x<<" "<<y;
}
}
}
}
}
你的算法可能有点太复杂了。 特别是运行循环总是 30000 次,即使没有必要,也会以某种方式浪费时间。
而且,如果您想请求输入大于 30000 的数字,它也将不起作用。
循环应该重写为: for (i = 1; count <= n; i++)
。 然后是应该更好。
如果你只是想有一个螺旋图案的xy坐标,你可以做下面的设计然后实现它。 查看图片,我们看到以下内容:
因此,请查看价格并相应地实施。
请参阅众多解决方案建议之一:
#include <iostream>
int main() {
// Get user input. How many steps shall we go in our spiral
unsigned int numberOfSteps{};
std::cin >> numberOfSteps;
int coordinate[2]{}; // Here we will store the xy coordinate. Index 0 = x, index 1 = y
int xySelector{}; // This will select either index 0 or 1 , so, either x or y
int delta{ 1 }; // This will be added to a coordinate part, to get the next point of the line
int distance{ 1 }; // Length of line. Will be used 2 times, then incremented
int distanceCounter{ 1 }; // Down counter for distance
int doSameDistanceCounter{ 2 }; // We will do always 2 lines with the same distance/length
// Do the game for the requested number of steps
for (int i{}; i < numberOfSteps; ++i) {
coordinate[xySelector] += delta; // Calculate next point of line
--distanceCounter; // Keep track of length of line
if (distanceCounter == 0) { // Did we calculate one complete line?
xySelector = 1-xySelector; // Yes, then now use the other coordinate
--doSameDistanceCounter; // Keep tract of number of same line length to use
if (doSameDistanceCounter == 0) { // If we did 2 lines with the same length
doSameDistanceCounter = 2; // Reset this counter
++distance; // Frome now one the length of line will be 1 more
delta = -delta; // And the delta changes, fo increment or decrement operation changes
}
distanceCounter = distance; // Reset distance/length counter to current needed distance
}
} // Show result
std::cout << coordinate[0] << ' ' << coordinate[1] << '\n';
}
我在发布模式下用 10M 对其进行了测试,结果非常快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.