在使用code :: blocks IDE和C ++解决问题时,类似的表达式result[i] += ((res*1.0 /10)-(res/10)) * 10;
,如果赋值为result[i]
7后正确表达式的结果为8,则result[i]
保留7而不是8。
这是整个函数:它需要两个数字并将每个数字转换为数组。例如34变为{4,3}
,所以我将数字添加为数组,而不是常规数字。
void add(char a, char b)
{
//get # digits of both
int n1=0;
int n2=0;
char temp1=a;
char temp2=b;
//counting # digits of first number
while( (temp1*1.0/10) != 0 )
{
n1++;
temp1/=10;
}
//counting # digits of second number
while( (temp2*1.0/10) != 0 )
{
n2++;
temp2/=10;
}
int maxi=max(n1,n2);
int mini=min(n1,n2);
//filling arr1 arr2
char * arr1=new char[n1];
char * arr2=new char[n2];
char * result=new char[maxi+1];
//fill result with zeros
for(int k=0; k<maxi+1; k++)
result[k]=0;
temp1=a;
for(int i=0; i<n1; i++)
{
arr1[i]=((temp1*1.0 /10)-(temp1/10)) * 10;
temp1/=10;
}
temp2=b;
for(int j=0; j<n2; j++)
{
arr2[j]=((temp2*1.0 /10)-(temp2/10)) * 10;
temp2/=10;
}
//add both arrays
char res=0;
char overflow=0;
for(int i=0; i<maxi; i++)
{
if(i<mini)
{
res=arr1[i]+arr2[i];
if(checkDigit(res))
{
result[i]=res;
}
else
{
////////////////////////////
//>>>>>>>> result[i] += ((res*1.0 /10)-(res/10)) * 10;
///////////////////////////
overflow=res/10;
result[i+1]=overflow;
}
}
else
{
if(n1<n2)
{
result[i]+=arr2[i];
}
else if(n2<n1)
{
result[i]+=arr1[i];
}
}
}
if(!checkDigit(result[maxi-1]))
{
// assign overflow before
result[maxi]=result[maxi-1]/10;
result[maxi-1]=((result[maxi-1]*1.0 /10)-(result[maxi-1]/10)) * 10;
}
for(int i=0; i<maxi+1; i++)
cout<<(int)result[i]<<endl;
}
您正在执行浮点运算。计算机上的浮点操作不是特别准确。无论如何,base10都不适用。可能发生的是您的结果类似于7.9999999999991。标准库中的各种文本流会将其打印为8,但事实并非如此。然后,当您分配给result[i]
char(整数类型)时,您会得到标准的“在。之后将所有内容都切掉”。编译器的响应。
对此的简单响应是四舍五入操作。将.5添加到结果中,然后转换为整数。尽管根据您要解决的问题,但是有多种解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句