This is my code and what I want to do is (1)Take two numbers, (2)Multiply both numbers, (3)Return the product. It should work well without the scanf() but now I'm trying to use the scanf() to input a number via the terminal. Anyone knows what's wrong?
#include <stdio.h>
int multiply(int num1, int num2) {
int product = num1 * num2;
return product;
}
int main() {
scanf("%d %d", num1, num2);
int result = multiply(num1, num2);
printf("%d x %d = %d", num1, num2, result);
return 0;
}
I tried running the code and it says undeclared num1 and num2. Doesn't num1 and num2 get declared in the multiply function?
CodePudding user response:
Basically you want this:
int main() {
int foo, bar;
scanf("%d %d", &foo, &bar); // you forgot the &
int result = multiply(foo, bar);
printf("%d x %d = %d", foo, bar, result);
return 0;
}
- you forgot the & in front of the variables with
scanf
. It's explaind somewhere in your C book - variables declared in
multiply
are only visible (and they even only exist) inside ofmultiply
. This is also explaind in your C book in the chapters dealing with functions.
BTW the code below is equivalent to the code above. The variables num1
and num
declared in main
are not related at all to the variables num1
and num2
in multiply
, they just happen to have the same name.
int main() {
int num1, num2;
scanf("%d %d", &num1, &num2); // you forgot the &
int result = multiply(num1, num2);
printf("%d x %d = %d", num1, num2, result);
return 0;
}