#define _CRT_SECURE_NO_WARNINGS
#include
int check(int n);
int main()
{
int count = 0;
for (int i = 1; i <=2020; i++)
{
/*int n = i;
while (n)
{
if (n % 10 == 2)
count++;
n/= 10;
}*/
/* count += check(i);*/
if (check(i))
count++;
}
printf("%d", count);
return 0;
}
int check(int n)
{
int count = 0;
while (n!=0)
{
if (n%10==2)
{
/*count++;*/
return 1;
}
n /= 10;
}
//return count;
}
我用很多种方式,注释的部分方式都可以算出答案,为什么我没注释的部分算出的答案是错的,它是563,少计算了,逻辑应该是对的啊
参考GPT和自己的思路:
根据你提供的代码,我发现出错的原因在于你没有删除注释的部分,即改动了代码的结构而没有更新所有的语句。在这里,注释的代码会使得计数器 count
多加多个值,这就导致了最终结果的不同。如果你想要注释的代码起到作用,你需要将 count++
放到 while
循环中,这样就可以正确计算了。如果你不想用注释的代码,那么直接使用 check
函数即可。
断言时还要判断队列是否为空,即assert(pq->head&&pq->tail);
这里要注意为什么判断的时head的next是否为空而不是直接判断head:
若队列只有一个结点时,此时head=tail,head指向next,head置空,但此时tail还指向原head的位置,会造成野指针的问题。
//出队
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->head&&pq->tail);
if (pq->head->next==NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
}