计算3位数字的位数的和

问题描述 投票:0回答:2

我写了这个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);
}
c++ factorial
2个回答
1
投票

num的数字不是num % 100num % 10,num % 1。无论是什么给了你这个想法?

num=567为例。然后我们有

num % 100 = 67

num % 10 = 7

num % 1 = 0

你需要多考虑一下。


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);
}
© www.soinside.com 2019 - 2024. All rights reserved.