T
T
timur1022019-01-13 17:02:26
C++ / C#
timur102, 2019-01-13 17:02:26

Why is the program not working correctly?

There is a program that calculates something:

#include <stdio.h>

int count_of_combinations(int k, int n);
int factorial (int n);

int main(){
  int n = 0,k = 0, count;
  int sub_factorial[10] = {0, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496};
  scanf("%d%d", &n, &k);
  int combinations = sub_factorial[n-k];
        int q = factorial(n);
        int q1 = factorial(n-k);
        int q2 = factorial(k);
  count = count_of_combinations(n,k);
  printf("%d\n", count*combinations);


  return 0;

}

int count_of_combinations(int n, int k){
  return factorial(n) / (factorial(k) * factorial(n-k));
}


int factorial (int n)
{
  return (n < 2) ? 1 : n * factorial (n - 1);
}

And the whole problem is that the variable q2 takes on a random value at k = 1
And after the execution q2 = 1 (it should be)
Here is what gdb says:
Reading symbols from ./prog...done.
(gdb) b 13
Breakpoint 1 at 0x1214: file prog.c, line 13.
(gdb) b 17
Breakpoint 2 at 0x124d: file prog.c, line 18.
(gdb) r
Starting program: ./prog
9 1

Breakpoint 1, main () at prog.c:13
13		int q2 = factorial(k);
(gdb) p q2
$1 = 1431655213
(gdb) p k
$2 = 1
(gdb) c
Continuing.
133497

Breakpoint 2, main () at prog.c:18
18		return 0;
(gdb) p k
$3 = 1
(gdb) p q2
$4 = 1

Why? Where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dedalqq, 2019-01-14
@timur102

This is what confuses me: scanf("%d%d", &n, &k);
I suspect that some kind of ambiguous behavior. try replacing that with
scanf("%d", &k);
scanf("%d", &n);
PS
and in general, in my opinion it's easier to get it from the parameters =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question