我使用float
时遇到问题在循环中它的值停留在8388608.00
int count=0;
long X=10;
cout.precision(flt::digits10);
cout<<"Iterration #"<<setw(15)<<"Add"<<setw(21)<<"Mult"<<endl;
float Start=0.0;
float Multiplication = Addition * N;
long i = 1;
for (i; i <= N; i++){
float temp = Start + Addition;
Start=temp;
count++;
if(count%X==0 && count!=0)
{
X*=10;
cout<<i;
cout<<fixed<<setw(30)<<Start<<setw(20)<<fixed<<i*Addition<<endl;
}
}
我该怎么办?
答案 0 :(得分:3)
Floating point addition不起作用。这是由float is stored in memory的方式引起的。
您可以尝试将single precision floating point(float
)替换为double precision floating point(double
),但如果这不起作用,您可能需要实施这样的黑客攻击:
// Lets say
double OriginalAddition = 0.123;
int Addition = 1;
// You just use base math substitution:
// Addition = OriginalAddition
int temp = Start + Addition; // You will treat transform floating point to fixed point
// with step 0.123, so 1 = 0.123
// And when displaying result (transform back into original floating point):
printf( "%f", (double)result*OriginalAddition)
需要花费很多心思找到不会导致数据丢失的替代,涵盖所需的精度并且不会导致int
溢出。尝试谷歌fixed point int C(一些结果:1,2)以更好地了解该怎么做。