我写了这个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);
}
num
的数字不是num % 100
,num % 10,
和num % 1
。无论是什么给了你这个想法?
以num=567
为例。然后我们有
num % 100 = 67
num % 10 = 7
num % 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);
}