为什么我的阶乘程序在C中返回0?

时间:2015-03-13 02:16:06

标签: c

所以我正在用C编写我的第一个程序,而我正在尝试编写一个阶乘函数,但它似乎没有工作,我不知道为什么。

#include <stdio.h>

int x = 5;
int counter;

int factorial (int x)
{
  int counter = 1;

  for ( x > 0; x<= 100;)
    counter = counter * x;

  x = x - 1;
}

int main (int factorial)
{
  printf ("%i", counter);
}

所以,是不是真的不知道为什么这不起作用?任何帮助:)

2 个答案:

答案 0 :(得分:1)

更新回答

//int x = 5; this isn't doing anything
//int counter; not doing anything

int factorial(int x)
{
    int counter = 1;
    /*
    for (x > 0; x <= 100;)
        counter = counter * x;
    1) x is input, don't use as counter, not in this case anyway
    2) The variable 'counter' is where x is supposed to be
    3) the loop is infinite
    */

    x = 1; //initialize x
    for (counter = 1; counter <= x; counter++)
        x = x * counter;

    //x = x - 1; shouldn't be here

    //x has to be returned
    return x;
}

//int main(int factorial) //don't put random arguments in main
int main() 
{
    //call the function
    printf("%i", factorial( 5 ));
    return 0;
}

答案 1 :(得分:0)

基本上,您不是在调用该函数,因此会打印出计数器的初始值(即垃圾值)。