我已经编写了此c ++代码,以计算三位数的数字的阶乘和,但它不起作用:
输出为:
返回的过程-1073741571(0xC00000FD)执行时间:9.337 s 按任意键继续。
#include <iostream>
#include <exception>
using namespace std;
unsigned fact(int n)
{
if (n == 1|n==0)
return 1;
else
return n * fact(n - 1);
}
int main()
{
int num;
int sum=0;
int tmp;
cout<<"Enter 3 digit number:\n";
cin>>num;
if(num<99|num>999)
{
cout<<"Not a 3 digit number!";
return (1);
}
tmp = num%100;
sum = sum+ fact(tmp);
tmp = num%10;
sum = sum+ fact(tmp);
tmp = num%1;
sum = sum+ fact(tmp);
cout<<"Sum of factorial of digits in a number:"<<sum;
return(0);
}
答案 0 :(得分:1)
num
的数字不是num % 100
,num % 10,
和num % 1
。是什么给了你这个主意?
以num=567
为例。然后我们有
num % 100 = 67
num % 10 = 7
num % 1 = 0
您需要再考虑一下。
答案 1 :(得分:0)
我忘记了如何选择现在可以使用的数字:
#include <iostream>
#include <exception>
using namespace std;
unsigned fact(int n)
{
if (n == 1||n==0)
return 1;
else
return n * fact(n - 1);
}
int main()
{
int num;
int sum=0;
int tmp;
cout<<"Enter 3 digit number:\n";
cin>>num;
if(num<=99|num>999)
{
cout<<"Not a 3 digit number!";
return (1);
}
tmp = num%10;
sum = sum+ fact(tmp);
tmp = num/10%10;
sum = sum+ fact(tmp);
tmp = num/100%10;
sum = sum+ fact(tmp);
cout<<"Sum of factorial of digits in a number:"<<sum;
return(0);
}