算阶乘,结果老是e=1,“factorial()”是个算阶乘的函数
不知道哪出了问题……
代码:
#include <iostream>
#include <string>
using namespace std; int factorial(int i)
{
int nfactorial=1;
while(i>1){
nfactorial*=i;
--i;
}
return nfactorial;
}int main(){
float e;
for(int j=0;j<20;j++)
{
e=1+1.0/factorial(j);
}
cout<<"e = "<<e<<endl;}
不知道哪出了问题……
代码:
#include <iostream>
#include <string>
using namespace std; int factorial(int i)
{
int nfactorial=1;
while(i>1){
nfactorial*=i;
--i;
}
return nfactorial;
}int main(){
float e;
for(int j=0;j<20;j++)
{
e=1+1.0/factorial(j);
}
cout<<"e = "<<e<<endl;}
解决方案 »
- MoveWindow()运行出错!!
- GetSystemDefaultUILanguage返回值到底是什么
- 对话框过程中怎么得到窗口句柄?
- 如何在服务程序中得到administrator权限
- 请教WaitForSingleObject(aHandle, 3000)
- 十万火急!十万火急!十万火急!十万火急!我的ObjectARX少一个头文件,谁有?谁有?谁有?
- 如何获得鼠标点在位图上的坐标
- 处于死循环的窗口无法接收消息,如何解决?
- 宏定义问题
- 求问 关于2个线程传递参数 造成2个参数的数据改变的问题
- 多文档切分的问题
- 希望和大家探讨一些 "XX游戏对战平台" 的实现细节. 有兴趣的请参与. 关键字: P2P,DLL注入,虚拟局域网,VPN,VLAN
+1后,取舍有效位即1.000000,所以结果总是1
float e=0;
for(int j=0;j<20;j++)
{
e+=1.0/factorial(j);
cout<<"e = "<<e<<endl;
}
}
我按lang801213() 的来做就弄好了,这是算“欧拉数”的,我要的也是这个
vcmute()说的也是对的,因为我的这个程序算的是1/(20的阶乘)了
是我没问好~不用换成double的也行的
谢谢大家
最后我想要的代码:
#include <iostream>
#include <string>
using namespace std;
int factorial(int i)
{
int nfactorial=1.0;
while(i>1){
nfactorial*=i;
--i;
}
return nfactorial;
}int main(){
float e=0;
for(int j=0;j<20;j++)
{
e+=1.0/factorial(j);
}
cout<<"e = "<<e<<endl;
}
结果是e=0.71828
别人的代码,不要问我为什么^-^.#include <vector>
#include <cmath> // log10
#include <cstdlib> // strtol
#include <algorithm> // for_each
#include <iostream>
#include <iomanip> // setw, setfill
#include <Windows.h>
using namespace std;void print4d(int d)
{
cout << setw(4) << setfill('0') << d;
}int main(int argc, char* argv[])
{
long n;
vector<long> fac;
fac.reserve(10000000);
DWORD time,time1,time2;
vector<long>::iterator i,first,second; long carry=0;
long j=1;
ULONG product;
bool bGetFuc;
HANDLE hProcess=::GetCurrentProcess();
SetPriorityClass( hProcess, REALTIME_PRIORITY_CLASS);
while(true)
{
if (1 == argc) {
cout << "Input N = ";
cin >> n;
} else { // get n from command line
n = strtol(argv[1], (char **)NULL, 10);
} if(0==n)
return 0;
fac.clear();
fac.push_back(1);
bGetFuc=true;
carry=0;
j=1; time1=::GetTickCount();
for ( ; j <= n; ++j) {
carry = 0;
if(bGetFuc)
{
first=fac.begin();
second=fac.end();
} for (i=first; i!=second; ++i) {
product = *i * j + carry;
carry = product / 10000;
*i = product - carry * 10000;
}
bGetFuc=false;
if (carry) {
bGetFuc=true;
if(carry<10000)
fac.push_back(carry);
else
{
fac.push_back(carry%10000);
fac.push_back(carry/10000);
}
}
}
time2=::GetTickCount();
time=time2-time1;
// cout << *fac.rbegin();
//for_each(fac.rbegin() + 1, fac.rend(), print4d); {int digits = 4 * fac.size() + int(log10(double(*fac.rbegin()))) - 3;
cout << "\nTotal: " << digits << " digits\n";}
cout<<endl<<"总共用时是:"<<time<<"豪秒,输入0结束程序";
system("PAUSE");
}
}