【问题标题】:My c program is not giving any result.pls help everyone [closed]我的c程序没有给出任何结果。请帮助大家[关闭]
【发布时间】:2016-02-24 16:49:09
【问题描述】:

我编写的程序没有给出正确的结果。

main()
{
    int i=1,n,s=1;
    printf("enter the value of n");
    scanf("%d",&n);

    while(i<=n) 
    {
         s=s*i;
         i++;
         if (i==n+1)
         {
             break; 
         }
    }
    printf("factorial of n=",s);
}

它给出的结果如下图所示。

【问题讨论】:

  • 不要发布文字图片!
  • 你没有打印s的值。

标签: c loops factorial


【解决方案1】:

你的问题出在这一行:

printf("factorial of n=",s);

这会输出factorial of n=,但它并没有简单的将s的值串联起来,而且s没有占位符,所以实际上你的参数太多了。

int 输出需要占位符:

printf("factorial of n=%d",s);

没有它,您的程序将退出并出现错误(状态 15,当 0 为正常时)。

另外,(正如弗拉德在他的回答中指出的那样)if (i==n+1) { ... } 块是多余的,因为当i &gt; n 时,您的while 循环已经退出。

【讨论】:

    【解决方案2】:

    printf("factorial of n=%d\n",s);
                           ^^
    

    还有这段代码sn-p

         if (i==n+1)
         {
             break; 
         }
    

    是多余的,可能会被删除。

    您可以更简单地编写循环。例如

    while ( n > 1 ) s *= n--;
    

    无需再使用一个变量i

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      相关资源
      最近更新 更多