我编写了一段代码,在创建 myFactorial 函数后计算阶乘,但是当我尝试处理更大的数字时,我把它搞砸了。
我正在尝试使用长格式处理 16 以上的数字,但结果无关紧要,并且代码的第二部分事情变得更奇怪。 虽然结果不应随输入而改变,但它们确实会改变!
我通过下面的评论分享我的代码:
main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int yourNumber;
int i;
//Take the input
printf("I highly recommend you to make the command window fullscreen. Otherwise, the complete output will not be seen.\n");
printf("Enter a positive integer and I will tell you its factorial.\n");
scanf("%d", &yourNumber);
//Calculate factorial and print it in three ways
printf("Factorial of %d is %d!\n",yourNumber,myFactorial(yourNumber));
printf("Using long format, factorial of %d is %lld!\n",yourNumber,myFactorial(yourNumber));
printf("In hex: %#08X!",myFactorial(yourNumber));
// Here on, second part of my code begins
// Calculate and print factorials of numbers from 1 to 20 in %d format
printf("\n\n\nLet's see more d's!\n\n");
for (i = 1; i<21; i++) printf("%d\n", myFactorial(i));
// Calculate and print factorials of numbers from 1 to 20 in %lld format
printf("\n\n\nNow let's see more lld's!\n\n");
for (i = 1; i<21; i++) printf("%lld\n", myFactorial(i));
return 0;
}
myfactorial.c
#include <stdio.h>
long long int myFactorial(int bar) {
long long out = 1;
int i;
for (i=1; i<=bar; i++)
{
out *= i;
}
return out;
}
最佳答案
您的 printf
有问题格式:
全部printf
打印 myFactorial 的返回值必须使用 %lld
格式,为long long int
printf
打印十六进制值必须使用 %llX
打印正确的值
//Calculate factorial and print it in three ways
printf("Factorial of %d is %lld!\n",yourNumber,myFactorial(yourNumber));
printf("Using long format, factorial of %d is %lld!\n",yourNumber,myFactorial(yourNumber));
printf("In hex: %#016llX!",myFactorial(yourNumber));
// Here on, second part of my code begins
// Calculate and print factorials of numbers from 1 to 20 in %d format
printf("\n\n\nLet's see more d's!\n\n");
for (i = 1; i<21; i++) printf("%lld\n", myFactorial(i));
// Calculate and print factorials of numbers from 1 to 20 in %lld format
printf("\n\n\nNow let's see more lld's!\n\n");
for (i = 1; i<21; i++) printf("%lld\n", myFactorial(i));
您只需添加 -Wall
即可找到此类错误使用 gcc 编译时的选项。它会告诉你
test.c: In function ‘main’:
test.c:84:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long long int’ [-Wformat=]
printf("Factorial of %d is %d!\n",yourNumber,myFactorial(yourNumber));
^
test.c:86:5: warning: format ‘%X’ expects argument of type ‘unsigned int’, but argument 2 has type ‘long long int’ [-Wformat=]
printf("In hex: %#08X!",myFactorial(yourNumber));
^
test.c:94:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long long int’ [-Wformat=]
for (i = 1; i<21; i++) printf("%d\n", myFactorial(i));
最好添加以下所有选项:-Wall -Wextra -pedantic
Take note that your code can work correctly as far as the factorial is less then
9223372036854775807
that is the maximum allowed forlong long int
这意味着您可以计算阶乘,其中 x <= 20
关于c - 计算阶乘时的长格式处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38217599/