简体   繁体   English

为什么在 C 中查找阶乘的 FOR 循环后没有大括号

[英]Why the absence of curly brackets after FOR loop in finding factorials in C

This is one of the code to find the factorial of a given non negative integer.这是查找给定非负整数的阶乘的代码之一。 When I use the curly brackets after FOR loop for this code, the program runs very slowly.当我在此代码的 FOR 循环后使用大括号时,程序运行速度非常慢。 I know that for loops can be used without curly brackets for single line of code , but my code consists of two lines within the for loop.我知道 for 循环可以在没有大括号的情况下用于单行代码,但我的代码由 for 循环中的两行组成。 Can someone explain the reason for this ?有人可以解释原因吗?

#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);
  
  
 }

I have used rextester c compiler to analyze the run time of your program and I could see,我已经使用rextester c 编译器来分析你的程序的运行时间,我可以看到,

without curly brackets running time : 0.18 sec and with curly brackets running time : 0.16 sec , which might vary time to time for approx +/- 0.05 sec.不带大括号运行时间: 0.18 秒,带大括号运行时间: 0.16 秒,可能会不时变化约 +/- 0.05 秒。 And if you are using or not using a curly brackets for the single line code in a loop which I guess should not affect the run time of the program.而且,如果您在循环中对单行代码使用或不使用大括号,我想这不会影响程序的运行时间。

You can use some other compiler and try running your code.您可以使用其他一些编译器并尝试运行您的代码。

you are absolutely right when saying你说的完全正确

for loops can be used without curly brackets for single line of code for 循环可以在没有大括号的情况下用于单行代码

more precisely for loop will run only one line of code if not provided with any curly braces更确切地说for loop将只运行一行代码,如果不设置任何大括号

so your code所以你的代码

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

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

will be same as将与

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

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

but here you are putting braces ( {} ) around both fact=fact*i;但是在这里,您在fact=fact*i;周围放置了大括号( {}fact=fact*i; and printf("value of factorial %d is %d",input,fact);printf("value of factorial %d is %d",input,fact);

so just like @Some programmer dude said in comments section, in this case both of these statements will be executed on each iterations of the loop and thus will be comparatively slower than the first one.所以就像@Some程序员哥们在注释部分所述,在这种情况下这两个语句将在循环的每个迭代执行的,因此将是相对慢于第一个。 But still that should not make big of a difference in terms of total execution time.但这仍然不会对总执行时间产生太大影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM