计算一个 3 位数字的阶乘和

calculate sum of factorials of digits of a 3 digit number

我已经编写了这个 c++ 代码来计算三位数的阶乘之和,但它不起作用:

输出为:

进程返回 -1073741571 (0xC00000FD) 执行时间:9.337 秒 按任意键继续。

#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);
}

num的数字不是num % 100num % 10,num % 1。是什么让你产生了这个想法?

num=567为例。那么我们有

num % 100 = 67

num % 10 = 7

num % 1 = 0

你需要多考虑一下。

我忘记了如何 select 现在有效的数字:

#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);
}