用户输入的因子问题

时间:2014-04-06 03:11:59

标签: c factorial

我正在学习c语言,我对下面的代码感到困惑。它是一个递归,但是当我运行这个代码时,它将不会运行,直到我提供了2个不同的输入,但系统只执行第一个?

提前致谢。

#include <stdio.h>

long factor (float user_input)
{
if(user_input <=1)
return 1;
else
return (user_input * factor (user_input - 1));
}

int main ()
{
int user_input;
long factorial_calculation;
printf("what factorial number would you like to calculate?\n");
scanf("%d\n", &user_calculation);
factorial_calculation = factor (user_input);
printf("ld\n", factorial_calculation);
return 0;
}

2 个答案:

答案 0 :(得分:4)

  1. 您的user_inputint,但您将变量作为float传递并在其上运行您的阶乘函数。对于非整数nos,因子是未定义的,因此最好使用int

  2. 在:

    printf("ld\n", factorial_calculation);
    

    ld是无效的格式说明符。

  3. scanf("%d\n", &user_calculation);
    

    我认为你的意思是

    scanf("%d", &user_input);
    
  4. 以下代码有效:

    #include <stdio.h>
    
    int factor (int user_input)
    {
        if(user_input <=1)
            return 1;
        else
            return (user_input * factor (user_input - 1));
    }
    
    int main ()
    {
        int user_input;
        long factorial_calculation;
        printf("what factorial number would you like to calculate?\n");
        scanf("%d", &user_input);
        printf("%d\n",user_input);
        factorial_calculation = factor (user_input);
        printf("%d\n", factorial_calculation);
        return 0;
    }
    

答案 1 :(得分:2)

众所周知,

scanf()很难与用户输入同步。相反,使用fgets()并检查字符串中的数字(如果每行预计有多个数字,则检查数字)。

long factorial_calculation;
char buf [1000];
for (;;)
{
    printf("What factorial number would you like to calculate?\n");
    if (!fgets (buf, sizeof buf, stdin))  /* probably EOF, hangup, etc.:  just exit */
        return 0;
    if (1 != sscanf(buf, "%ld", &user_calculation))
    {
        printf ("No number entered, please try again\n");
        continue;
    }
    factorial_calculation = factor (user_input);
}