我在codechef上解决了一个非常简单的问题(计算平方根),但当我运行代码时,它显示超过了时间限制。然后,我查看了其中一个提交的解决方案,发现两个代码之间唯一的区别是声明变量的顺序。
以下是运行正常的代码
#include<stdio.h>
#include<math.h>
main()
{
int ans,n,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
ans=sqrt(n);
printf("%d\n",ans);
}
}下面是我的代码,它不能工作
#include<stdio.h>
#include<math.h>
main()
{
int t,n,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
ans=sqrt(n);
printf("%d\n",ans);
}
}唯一的区别是声明变量的顺序不同。
发布于 2020-12-18 16:37:22
未指定如何将声明的顺序转换为寄存器或堆栈偏移量。因此,这取决于编译器,如果顺序有区别的话。您可以比较程序集输出的差异。但是在scanf和printf之间,您应该看不到任何相关的时序差异。
https://stackoverflow.com/questions/65352991
复制相似问题