如何使长整型数在取模后保持长度不变,例如一个19位数(次高位为零)再取10的18次幂的模后,能保证数字长不变,不足长度最高位补零.
我写了一个计算斐波那契数列的程序,按照你的方法,结果很悲剧.
#include <stdafx.h>
#include <iostream>
#include <limits.h>
#include <malloc.h>
using namespace std;
int main(void)
{
int n;
cout<<"请输入Fabonacci数列所求数个数:";
cin>>n;
long long int *a;
a=(long long int*)malloc(sizeof(long long int));
a=new long long int[n];
int i=2;
a[1]=1;
a[2]=1;
a[3]=2;
int m;
int odd=2;
int even=0;
if (n>2)
{
cout<<"第1个数是1是奇数"<<endl;
cout<<"第2个数是1是奇数"<<endl;
do
{
i++;
a[i]=a[(i-1)]+a[(i-2)];
cout<<"第"<<i<<"个数是"<<a[i];
m=a[i]%2;
switch(m)
{
case 0:
cout<<"是偶数"<<endl;
even++;
if (a[i]>1000000000000000000)
{
goto BIGNUM;
}
continue;
case 1:
cout<<"是奇数"<<endl;
odd++;
if (a[i]>1000000000000000000)
{
goto BIGNUM;
}
continue;
}
}while(i<n);
goto END;
}
if (n==1)
{
cout<<"第1个数是1"<<endl;
cout<<"前1个数共有0个偶数"<<endl;
cout<<"前1个数共有1个奇数"<<endl;
goto END;
}
if (n==2)
{
cout<<"第1个数是1"<<endl;
cout<<"第2个数是1"<<endl;
cout<<"前2个数共有0个偶数"<<endl;
cout<<"前2个数共有2个奇数"<<endl;
goto END;
}
if (n<=0)
{
cout<<"错误!"<<endl;
goto END;
}
BIGNUM:long long int a1;
long long int a2;
long long int a3;
long long int b1;
long long int b2;
long long int b3;
long long int c1;
long long int c2;
long long int c3;
a1=0;
b1=a[(i-1)];
a2=1;
b2=a[i]-1000000000000000000;
i++;
for (i=i;i<=n;i++)
{
b3=(b1+b2)%1000000000000000000;
a3=(a1+a2)+(b1+b2)/1000000000000000000;
cout<<"第"<<i<<"个数是"<<a3<<b3;
m=b3%2;
a1=a2;
b1=b2;
a2=a3;
b2=b3;
switch(m)
{
case 0:
cout<<"是偶数"<<endl;
even++;
if (a3>1000000000000000000)
{
goto LBIGNUM;
}
continue;
case 1:
cout<<"是奇数"<<endl;
odd++;
if (a3>1000000000000000000)
{
goto LBIGNUM;
}
continue;
}
}
goto END;
LBIGNUM:b1=a1;
b2=a3-1000000000000000000;
c1=b1;
c2=b3;
a1=0;
a2=1;
i++;
for (;i<=n;i++)
{
c3=(c1+c2)%1000000000000000000;
b3=((b1+b2)+(c1+c2)/1000000000000000000)%1000000000000000000;
a3=((a1+a2)+(b1+b2)/1000000000000000000)%10000000000000000000;
cout<<"第"<<i<<"个数是"<<a3<<b3<<c3;
m=c3%2;
a1=a2;
b1=b2;
c1=c2;
a2=a3;
b2=b3;
c2=c3;
switch(m)
{
case 0:
cout<<"是偶数"<<endl;
even++;
continue;
case 1:
cout<<"是奇数"<<endl;
odd++;
}
}
END:
cout<<"在Fabonacci数列前"<<n<<"个数共有"<<even<<"个偶数"<<endl;
cout<<"在Fabonacci数列前"<<n<<"个数共有"<<odd<<"个奇数"<<endl;
cout<<"请输入任意字符按回车结束"<<endl;
cin>>n;
}
有的数比前一个数更小,结果研究发现是取模运算时出了问题.作者: fwbook 时间: 2010-8-10 20:35