C 尝试将阶乘部分转换为另一个函数
我得开始感谢你们的帮助。我正试图将代码的阶乘部分转换为另一个函数,并想知道是否需要在C 尝试将阶乘部分转换为另一个函数,c,function,sum,factorial,C,Function,Sum,Factorial,我得开始感谢你们的帮助。我正试图将代码的阶乘部分转换为另一个函数,并想知道是否需要在 #include <stdio.h> #include <stdlib.h> int main() { int num; int indx; int arrayIndx; int accumulator; int fact; int individualDigit[50]; int length; for(indx = 999
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int indx;
int arrayIndx;
int accumulator;
int fact;
int individualDigit[50];
int length;
for(indx = 99999; indx > 0; indx--)
{
num = indx;
for (length = 0; num > 0; length++)
{
individualDigit[length] = num % 10;
num /= 10;
}
accumulator = 0;
for (arrayIndx = 0; arrayIndx < length; arrayIndx++)
{
fact = 1;
while(individualDigit[arrayIndx] > 0)
{
fact*= individualDigit[arrayIndx];
individualDigit[arrayIndx]--;
}
accumulator += fact;
}
if(accumulator == indx)
{
printf("%d ", accumulator);
}
}
return 0;
}
#包括
#包括
int main()
{
int-num;
int indx;
int-arrayIndx;
int累加器;
事实;
整数位数[50];
整数长度;
对于(indx=99999;indx>0;indx--)
{
num=indx;
对于(长度=0;数值>0;长度++)
{
individualDigit[长度]=数值%10;
num/=10;
}
累加器=0;
对于(arrayIndx=0;arrayIndx0)
{
事实*=单个数字[arrayIndx];
单个数字[arrayIndx]-;
}
累加器+=事实;
}
如果(累加器==indx)
{
printf(“%d”,累加器);
}
}
返回0;
}
您的程序设计得很糟糕。它没有缩进,您正在使用变量名index
、indx
和idex
,这会让读者感到困惑,并会导致长期维护的噩梦。此外,为了更好的模块化,阶乘计算应该放在函数中
但除此之外,您的程序会按您的要求执行,正确地计算阶乘并将它们添加到累加器
变量中。唯一的问题是,除了最后两种情况(2和1)中的n=n外,您从未打印该累加器代码>
只需替换:
if (accumulator == indx)
{
printf("\n%d\n", indx);
}
与
您将看到您的结果
如果要在数组中存储阶乘和,只需声明int-sumOfFact[26]={0}代码>就在int individualDigit[50]之前
定义数组并将sumOfFact[0]
初始化为1,然后添加sumOfFact[indx]=累加器代码>打印累加器之前
将阶乘部分放在函数中非常简单。首先在您的主菜单上方声明:
int ffact(int n);
用户可以在代码中的任何地方(如果需要,最终在另一个编译单元-a.c文件中)定义它
inf ffact(int n){
事实=1;
而(n>1){
事实*=n--;
/*if(fact<0){fprintf(stderr,“ffact(%d)\n)中的溢出”,n;返回0;}*/
}
返回事实
}
我注释掉了溢出测试,因为我假设您使用至少32位int,事实(9)不会溢出(但事实(13)会…)
计算阶乘和的循环变为:
accumulator = 0;
for (arrayIndx = 0; arrayIndx < length; arrayIndx++)
{
accumulator += ffact(individualDigit[arrayIndx]);
}
printf("\n%d\n", accumulator);
累加器=0;
对于(arrayIndx=0;arrayIndx
模块化的优点:单独测试ffact的代码更简单。因此,当出现问题时,您不必在一段超过40行的简单代码中爬行(不包括缺席但必要的注释)。而且,没有代码的代码混淆了<代码>个人数字< /COD>数组。< /P>您应该真正考虑缩进代码。为什么只有在代码>累加器= = DIX< <代码>的情况下打印累计值?这种情况背后的理由是什么?为什么不无条件地打印累加器
?我这样做是为了看看它是否真的将阶乘中的值相加。另外,请为循环变量选择更好的名称。看着索引
,indx
和idex
,我感觉像是在一个。它在for语句中。谢谢你的帮助,我把它清理了很多,并试图把阶乘方程变成一个函数,但不能。谢谢你。“溢出”到底是什么意思?@RichardFlores:在常见的体系结构上,int用32位表示,最重要的是符号位。12! 是479001600或0x1C8CFC000,十六进制,和13!六边形为6227020800或0x17328cc00。由于它使用超过32位,如果不测试任何内容,将得到错误的0x7328cc00或1932053504。如果进行测试,13*12*.3给出3113510400或0xb9946600,表示负值:-1181456896。欢迎来到处理器世界:-)
inf ffact(int n) {
fact = 1;
while (n > 1) {
fact *= n--;
/* if (fact < 0) { fprintf(stderr, "Overflow in ffact(%d)\n", n); return 0; } */
}
return fact
}
accumulator = 0;
for (arrayIndx = 0; arrayIndx < length; arrayIndx++)
{
accumulator += ffact(individualDigit[arrayIndx]);
}
printf("\n%d\n", accumulator);