69,369
社区成员
发帖
与我相关
我的任务
分享
#define MAX_PRECISION 16
#define MAX_LENGTH 50
char *dtoa(double d)
{
double t=d;
int qty=0;
int i=0;
int flag=0;
int max=0;
char *tmp=new char[MAX_LENGTH];
if (d<0.0)
{
tmp[i++]='-';
t*=-1;
}
while (t>1.0)
{
t/=10;
max=++qty;
flag=1;
}
while (qty>max-MAX_PRECISION)
{
if (qty==0&&flag==0)
{
tmp[i++]='0';
tmp[i++]='.';
}
tmp[i++]=(char)(floor(t*10)+48);
t=t*10-floor(t*10);
if (--qty==0&&qty!=max-MAX_PRECISION)
{
tmp[i++]='.';
}
if (qty==max-MAX_PRECISION&&t>0.5)
{
if (tmp[i-1]>='0'&&tmp[i-1]<'9') tmp[i-1]+=1;
}
}
tmp[i]=0x00;
return tmp;
}
void main()
{
double a=-12345123.5530089365;
cout.precision(MAX_PRECISION);
cout<<a<<endl;
cout<<dtoa(a)<<endl;
}
if(exponent>=0) //use >= instead of >
{ s[i++]='+';
}
#include "stdafx.h"
#include "math.h"
const int Accuracy=14;
const int signsize=1;
const int expsize=3;
const int FloatSize=signsize+2+Accuracy+2+expsize+1;
int _tmain(int argc, _TCHAR* argv[])
{ double x=0.0,y;
int exponent=0,i,j,c,temp;
char sign='+';
char s[FloatSize]={0};
printf("Input x : ");
scanf_s("%lf",&x);
if(x<0.0)
{ sign='-';
}
y=fabs(x);
if(y>1.0)
{ while(y>10.0)
{ y=y/10.0;
exponent++;
}
}
else if(y==1.0)
{
}
else
{ do
{ y=y*10.0;
exponent--;
}while(y<1.0);
}
//printf("%c%fe%d\n",sign,y,exponent);
i=0;
if(sign=='-')
{ s[i++]='-';
}
s[i++]=int(y)+'0';
y=y-(double)(s[i-1]-'0');
s[i++]='.';
j=i;
for(;i<Accuracy+j;i++)
{ y=y*10;
s[i]=int(y)+'0';
y=y-(double)(s[i]-'0');
}
y=y*10.0;
if(int(y)>=5)
{ c=1;
j=i-1;
while(c)
{ temp=s[j]-'0'+c;
c=temp/10;
s[j]=temp-10;
j--;
}
}
s[i++]='e';
if(exponent>0)
{ s[i++]='+';
}
else
{ s[i++]='-';
exponent=-exponent;
}
j=100;
while(exponent>0)
{ s[i++]=exponent/j+'0';
exponent=exponent%j;
j=j/10;
}
s[i]='\0';
printf("x=%s\n",s);
printf("x=%.14le\n",x);
//printf("x=%.14lf\n",x);
return 0;
}
#include "stdafx.h"
#include "math.h"
const int Accuracy=6;
const int signsize=1;
const int expsize=3;
const int FloatSize=signsize+2+Accuracy+2+expsize+1;
int _tmain(int argc, _TCHAR* argv[])
{ float x=0.0,y;
int exponent=0,i,j;
char sign='+';
char s[FloatSize]={0};
printf("Input x : ");
scanf_s("%f",&x);
if(x<0.0)
{ sign='-';
}
y=fabs(x);
if(y>1.0)
{ while(y>10.0)
{ y=y/10;
exponent++;
}
}
else if(y==1.0)
{
}
else
{ do
{ y=y*10;
exponent--;
}while(y<1.0);
}
//printf("%c%fe%d\n",sign,y,exponent);
i=0;
if(sign=='-')
{ s[i++]='-';
}
s[i++]=int(y)+'0';
y=y-(float)(s[i-1]-'0');
s[i++]='.';
j=i;
for(;i<Accuracy+j;i++)
{ y=y*10;
s[i]=int(y)+'0';
y=y-(float)(s[i]-'0');
}
y=y*10;
if(int(y)>=5)
{ s[i-1]++;
}
s[i++]='e';
if(exponent>0)
{ s[i++]='+';
}
else
{ s[i++]='-';
exponent=-exponent;
}
j=100;
while(exponent>0)
{ s[i++]=exponent/j+'0';
exponent=exponent%j;
j=j/10;
}
s[i]='\0';
printf("x=%s\n",s);
printf("x=%e\n",x);
printf("x=%f\n",x);
return 0;
}