[英]My factorial and power functions output a number in the millions when it shouldn't and I don't know how to fix it(in c)
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)
(我最近才刚开始学习C,所以假设我的知识范围就是这段代码中的全部内容)
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;
}
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);
Your printf
for the factorial and power cases are mal-formed, you are passing the arguments by pointer; 您的阶乘和幂情况的
printf
格式不正确,您正在通过指针传递参数; 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. 之后,您会很快意识到在阶乘和幂情况下
int
类型将会溢出。 An int
in general is only good up to and including 7!
一般而言,一个
int
最多只能包含7!
in truly portable C++. 在真正可移植的C ++中。 Consider using an
unsigned long long
, which will give you values up to and including 21!
考虑使用
unsigned long long
,这将使您的值最高为21!
. 。 Use
"%ull"
for an unsigned long long
in the formatter. 在格式化程序中使用
"%ull"
表示unsigned long long
。
Finally, pass the types explicitly to your functions in C: your style has been explicitly disallowed since C99. 最后,将类型显式传递给C语言中的函数:自C99以来,显式禁止使用您的样式。
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
打印结果,而你不及格要打印的实际值:
printf("The factorial is %i", &factorial);
You're passing in the address of factorial
instead of its value, so it's printing that instead. 您传递的是
factorial
的地址而不是其值,因此它将打印它。 Just pass the result directly instead of its address: 只需直接传递结果而不是其地址即可:
printf("The factorial is %i", factorial);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.