为什么在FOR循环后没有花括号在C

时间:2020-11-01 03:09:39

标签: c loops for-loop curly-braces

这是找到给定非负整数的阶乘的代码之一。当我在FOR循环后的花括号中使用此代码时,程序运行非常缓慢。我知道for循环可以不带大括号用于单行代码,但是我的代码由for循环内的两行组成。有人可以解释原因吗?

#include <stdio.h>
void main()
{

  int input,i,fact=1;
  
  //read user input//
  printf("Enter the number :");
  scanf("%d",&input);
  
  for(i=1;i<=input;i++)
  
   fact=fact*i;
   printf("value of factorial %d is %d",input,fact);
  
  
 }

2 个答案:

答案 0 :(得分:0)

我已经使用rextester c编译器来分析程序的运行时间,我可以看到,

不带花括号的运行时间: 0.18秒,并且 带有大括号的运行时间: 0.16秒,该时间可能会随时间变化大约+/- 0.05秒。而且,如果您在循环中的单行代码中使用或不使用大括号,我认为这不会影响程序的运行时间。

您可以使用其他一些编译器,然后尝试运行代码。

答案 1 :(得分:0)

你说的绝对正确

for循环可用于不带大括号的单行代码

更准确地说,for loop仅在没有任何花括号的情况下运行一行行代码

所以您的代码

for(i=1;i<=input;i++)
   fact=fact*i;

printf("value of factorial %d is %d",input,fact);

将与

相同
for(i=1;i<=input;i++)
  {
   fact=fact*i;
  }

   printf("value of factorial %d is %d",input,fact);

但是这里您在{}fact=fact*i;上都用大括号(printf("value of factorial %d is %d",input,fact);

就像评论部分中的@Some programmer dude一样,在这种情况下,这两个语句都将在循环的每次迭代中执行,因此,它们会比第一个慢比较。但这仍然不会在总执行时间上产生很大的差异。