-1

Hello friendly community, i´m really new in coding and also here registred on stackoverflow, so excuse me when I ask such simple questions. I lack the understanding to understand why this code does not work, because even after compiling no error message appears. My Code below shows my try to code a while loop, calculating the factioral and printing the total:

#include <stdio.h>

/*      Factorial 5! = 5*4*3*2*1      */

main ()
{
    int Wert;
    int fak = 1;

    scanf ("%d", Wert);

    while ( Wert > fak) {
        fak = fak * Wert;
        Wert = Wert - 1;
        printf ("%d", fak);
    }
}

It should calculate the factorial after input of a number and print the total. Maybe this can´t work but i don´t understand the why. Thank you for your time.

Eduard
  • 141
  • 7
  • Define *does not work* – CinCout Jul 22 '19 at 11:02
  • 4
    `while ( Wert > fak) {` ==> `while ( Wert > 1) {` – Support Ukraine Jul 22 '19 at 11:02
  • 3
    `scanf ("%d", Wert);` ==> `scanf ("%d", &Wert);`. Also, the compiler output here: https://ideone.com/hGPAb3 shows you the problem. – mch Jul 22 '19 at 11:03
  • Are you sure the compiler didn't give any diagnostics for that code ? If not, you should probably switch to a better one. – Sander De Dycker Jul 22 '19 at 11:07
  • 3
    Also, a code using 32-bit `int` is only good up to 12! after then it overflows. – Weather Vane Jul 22 '19 at 11:13
  • Would a `for` loop be better? – Ed Heal Jul 22 '19 at 11:27
  • I tried it with a FOR loop. Here the code: #include main() { int value; int fac; scanf ("%d", &value); for ( fac = 1; fac = fac * value; value = value - 1) { printf ("%d", fac); } } /* When i type 5 i should get "120" as a result, but the result is "52060120120" Can anyone explain and fix the result?*/ – Eduard Jul 30 '19 at 12:57

1 Answers1

2

Firstly, scanf expects the address of Wert, not its value, and also update your while loop to compare with 1. Here's the fixed version:

#include <stdio.h>

int main(void)
{
    int Wert;
    int fak = 1;

    scanf ("%d", &Wert);

    while ( Wert > 1 ) {
        fak = fak * Wert;
        Wert = Wert - 1;
    }
    printf ("%d", fak);
}

Input:

5

Output:

120

But since factorials easily overflow integers, it may be a better idea to use double instead:

#include <stdio.h>

double fact(double d)
{
    if (d < 1.0)
        return 1.0;
    return d * fact(d - 1.0);
}

int main(void)
{
    double d = 0;
    if (scanf("%lf", &d) != 1) {
        perror("Failed to read stdin");
        return -1;
    }
    printf("%lf! = %lf", d, fact(d));
    return 0;
}

Input:

100

Output:

100.000000! = 93326215443944102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

Just keep in mind that floating point math is broken.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93