阶乘程序不返回提示

阶乘程序不返回提示

该程序(factorial.c)正在运行,但它不会在结束时返回提示符,除非您按回车键:

#include <stdio.h>

int main()
{
  int num, i, fact = 1;

  printf("Enter a number to know its factorial: ");
  scanf("%d",&num);

  for(i=num;i>0;i--){
    fact = fact * i;
  }

  printf("Factorial of %d! = %d",num,fact);

  return 0;
}

编译并运行程序:

bash-4.2$ gcc factorial.c
bash-4.2$ ./a.out
Enter a number to know its factorial: 5
Factorial of 5! = 120bash-4.2$

当我按下回车键后:

bash-4.2$

答案1

printf这与通过命令行包含的行为相同。它也使用相同的 C 库来实现。注意行为:

$ printf "Factorial of %d! = %d" 4 24
Factorial of 4! = 24$

如果您希望它像这样显示,则必须包含文字换行符 ( \n) :printf

$ printf "Factorial of %d! = %d\n" 4 24
Factorial of 4! = 24
$

相关内容