Reputation: 29
I am trying to write a sort of calculator program and i can get everything but my factorial and power functions to work. They output a number in the millions no matter how small the number is and i don't see a problem with the code. (I just started learning C recently so assume the extent of my knowledge is everything in this code)
int iFactorial(num1){//needs help returns a number in the millions no matter what
int i, factorial=1;
printf("Enter a positive number: ");
scanf("%d", &num1);
for(i=1; i<=num1; i++)
factorial*=i;
printf("The factorial is %i", &factorial);
return 0;
}
int fPower(num1,num2){//needs help, same as above
int i, number = 1;
printf("Enter the number you want to raise to a power: \n");
scanf("%d", &num1);
printf("Enter the exponent: ");
scanf("%d", &num2);
for(i=0; i<num2; i++)
number*=num1;
printf("%d to the %d equals %d", &num1, &num2, &number);
return 0;
}
Upvotes: 1
Views: 49
Reputation: 234815
Your printf
for the factorial and power cases are mal-formed, you are passing the arguments by pointer; you need to pass them by value.
After that, you'll realise quickly that you'll overflow the int
type in the factorial and power cases. An int
in general is only good up to and including 7!
in truly portable C++. Consider using an unsigned long long
, which will give you values up to and including 21!
. Use "%ull"
for an unsigned long long
in the formatter.
Finally, pass the types explicitly to your functions in C: your style has been explicitly disallowed since C99.
Upvotes: 1
Reputation: 224522
You're using the wrong format specifiers to printf
to print the results, and you're not passing the actual values you want to print:
printf("The factorial is %i", &factorial);
You're passing in the address of factorial
instead of its value, so it's printing that instead. Just pass the result directly instead of its address:
printf("The factorial is %i", factorial);
Upvotes: 0
Reputation: 39
You are using & in the print statement that prints the address of the variable used. Correct the statements in their respective function as follows :
printf("The factorial is %i", factorial);
printf("%d to the %d equals %d", num1, num2, number);
Upvotes: 3