I am doing a assignment for class where the teacher is very partial about using scanf... I am not receiving the proper integer however. Is there something I am doing wrong with scanf? #include <cstdio>

#include<stdio.h>

#include<math.h>int main ()

{

int n, k, x, dif, combinations;

printf("Enter the number of items in the list (n):");

scanf("%d", &n);

while(n>9 || n<1)

{printf("Invalid input: Numbers must be between 1 and 10 \n"

"Enter the number of items in the list (n):");

scanf("%d", &n);

}

printf("Enter the number of items to choose (k): ");

scanf("%d", &k);

while(k>n || k<1)

{printf("Invalid input: Numbers must be between 1 and %d \n"

"Enter the number of items to choose (k):", &n);

scanf("%d", &k);

}/* Now starting the Math for Combinations */

dif=(n-k);

x=n-1; //needs to start one less for (n-1)

/* To get value of n! (n-k)! & k! */

while(x>1)

{

n=n*x;

dif=dif*x;

k=k*x;

x--;

}

/* End multiplication to figure out all possible combinations */

combinations=(n/dif*k);

printf("Number of combinations: %d ", &combinations);scanf("%d",&k);

return 0;

}

You don't say what the error is. The easiest way to solve a problem like this is to single-step in a debugger and watch what happens to the variable at each step. Just glancing at your code I don't think it should even compile, but I might br wrong. There is one glaring error near the end where you printf("string %d", &n), which will print the value of a pointer. I suspect you mean to print the value on n, not the address of n.

Learn how to use a debugger; it will teach you a lot.

Ick, scanf() is horrible and your teacher is horrible for having you use it. By extension, your teacher is a horrible person who probably kicks puppies in his off time. You probably need to flush any unwanted/invalid input. Read this.

I agree with Razor. I have never seen scanf used in any production code. That said, I see in two places a problem with the use of printf. You shouldn't need the address when printing a decimal:

This:

printf("Number of combinations: %d ", &combinations);

should be this:

printf("Number of combinations: %d ", combinations);

Ask Your Question

Weekly Poll

How long do you think until flying cars or taxis are common?

Discuss in The Lounge

Poll History