另一个“为什么我的 Uva 3n+1 解决方案不被接受?”问题
为什么我的解决方案失败了?
我写这篇文章的假设是stdin 是数据的来源。
我完全预计这是我的代码的问题,但我不明白为什么我会得到“错误答案”的结果。 (编译器选择是 ANSI C)
编辑:修改为允许参数 1 > param 2(但现在我得到“演示错误”,无论是什么)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
unsigned int p1;
unsigned int start;
unsigned int end;
unsigned int current;
unsigned int n;
unsigned int p2;
unsigned int max_cycle = 0;
unsigned int current_cycle;
while(scanf("%u %u", &p1, &p2) != EOF){
max_cycle = 0;
start = (p1 < p2 ? p1 : p2);
end = (p1 < p2 ? p2 : p1);
current = start;
while(current <= end){
n = current;
current_cycle = 0;
while(n > 1) {
if(n & 1)
n = 3*n+1;
else
n = n/2;
current_cycle++;
}
current_cycle++;
if (max_cycle < current_cycle) max_cycle = current_cycle;
current++;
}
fprintf(stdout, "%u %u %u\n", p1, p2, max_cycle );
}
return 0;
}
Why is my solution failing?
I wrote this under the assumption that stdin was the source of the data.
I fully expect that it is a problem with my code, but I am lost as to why I get 'Wrong Answer' as the result. (Compiler Choice was ANSI C)
EDIT: modified to allow parameter 1 > param 2 (but now I get "presentation error" whatever that is)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
unsigned int p1;
unsigned int start;
unsigned int end;
unsigned int current;
unsigned int n;
unsigned int p2;
unsigned int max_cycle = 0;
unsigned int current_cycle;
while(scanf("%u %u", &p1, &p2) != EOF){
max_cycle = 0;
start = (p1 < p2 ? p1 : p2);
end = (p1 < p2 ? p2 : p1);
current = start;
while(current <= end){
n = current;
current_cycle = 0;
while(n > 1) {
if(n & 1)
n = 3*n+1;
else
n = n/2;
current_cycle++;
}
current_cycle++;
if (max_cycle < current_cycle) max_cycle = current_cycle;
current++;
}
fprintf(stdout, "%u %u %u\n", p1, p2, max_cycle );
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
if (start == 0 || end == 0) continue;
不需要,结束条件是两者都为零,所以应该是if (start == 0 && end == 0) break;
也返回 0 并使其成为int main()
(至少在 ANSI CI 中知道,如果你不返回 0,无论如何都是错误的)。你还假设 i < j 但情况并非总是如此(据我所知)。祝你解决问题好运。if (start == 0 || end == 0) continue;
is unneeded the end condition is where both are zero so it should beif (start == 0 && end == 0) break;
Also return 0 and make itint main()
(at least in ANSI C I know if you dont return 0 its wrong no matter what). Also you're assuming i < j which is not always the case (as far as I remember). Good luck on solving it.