英文:
A possible test case I am missing out on?
问题
#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
for(int i=0;i<T;i++)
{
int N,K;
scanf("%d %d",&N,&K);
if(K!=0 && N>K)
{
printf("%d \n", (N%K));
}
else if(N<K)
{
printf("%d \n", N);
}
else
{
printf("0 \n");
}
}
return 0;
}
英文:
Problem statement
#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
for(int i=0;i<T;i++)
{
int N,K;
scanf("%d %d",&N,&K);
if(K!=0 && N>K)
{
printf("%d \n", (N%K));
}
else if(N<K)
{
printf("%d \n", N);
}
else
{
printf("0 \n");
}
}
return 0;
}
Now this is giving me the correct answer for the test case they have specified, but when I submit this, it doesn't get accepted. I know I am missing out on a test case which is not verified through the above code, but I am unable to wrap my head around it. Any help would be really appreciated!
答案1
得分: 1
如果K
为零,则结果应为N
。但是在第一个if
之后不必要的检查会强制将结果设置为0
。您可以通过消除这些不必要的检查来修复它。您也不需要检查N>K
,因为即使不满足条件,结果也将相同。您只需要:
if (K != 0)
{
printf("%d \n", N % K);
}
else
{
printf("%d \n", N);
}
独立于此,我不确定为什么会有尾随空格。您可能也想消除这些空格(它们进行了检查吗?)。您还可以使用如下所示的?:
来缩短它。还要注意,通过颠倒两种情况的顺序,还可以消除与零的显式比较:
printf("%d\n", K ? N % K : N);
这就是在scanf
之后您所需的一切。您不需要任何if
语句。如果K
为零,它会打印N
。否则,它会尽可能多地去除K
的倍数,这只是N%K
。
英文:
If K
is zero, the result needs to be N
. But the unnecessary checks after the first if
break this by forcing the result to 0
. You can fix it by eliminating those unnecessary checks. You also don't need to check if N>K
, since the result will be the same even if it isn't. All you need is:
if(K!=0)
{
printf("%d \n", N%K);
}
else
{
printf("%d \n", N);
}
Independent of this, I'm not sure why the trailing spaces are there. You might want to eliminate those as well (do they check for it?) You can also shorten it by using ?:
as shown below. Also note that by reversing the order of the two cases, the explicit comparison of K
with zero can be eliminated as well:
printf("%d\n", K ? N%K : N);
That's the all you need after the scanf
. You don't need any if
statements at all. If K
is zero, it prints N
. Otherwise it removes as many multiples of K
as possible, which is just N%K
.
答案2
得分: 1
你的解决方案存在问题的地方在于这段代码
{
printf("0 \n");
}
将会在两种情况下执行:
-
当K等于N时
-
当K为0(零)时
对于情况1,结果将为0(零),所以是正确的。
对于情况2,结果将为N,这就是你的错误。
对于完整的解决方案,我会简单地这样做:
printf("%d\n", (K == 0) ? N : N%K);
不需要嵌套的if
语句。你不需要特殊处理N < K
。
英文:
The problem with your solution is that this code
{
printf("0 \n");
}
will be executed in two situations:
-
When K equals N
-
When K is 0 (zero)
For number 1 the result will be 0 (zero) so that is correct.
For number 2 the result will be N so that is your bug.
For the complete solution I would simply do:
printf("&d\n", (K == 0) ? N : N%K);
No need for the nested if
-statements. You don't need a special handling of N < K
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论