知識社群登入
位置: AutoCAD開放式教學 > 討論區 > 討論
整數的 over- flow 背後的數學
1樓
#if 0

// double 算出來的正確值,和 整數算出來的 
因為 整數的 over- flow 的錯誤值之間的關係,如下:

no= 10
sum= 55,
 xs= 55

 js= 55

no= 20
sum= 210,
 xs= 210

 js= 210

no= 40
sum= 820,
 xs= 820

 js= 820

no= 80
sum= 3240,
 xs= 3240

 js= 3240

no= 160
sum= 12880,
 xs= 12880

 js= 12880

no= 320
sum= 51360,
 xs= 51360

 js= 51360

no= 640
sum= 205120,
 xs= 205120

 js= 205120

no= 1280
sum= 819840,
 xs= 819840

 js= 819840

no= 2560
sum= 3278080,
 xs= 3278080

 js= 3278080

no= 5120
sum= 13109760,
 xs= 13109760

 js= 13109760

no= 10240
sum= 52433920,
 xs= 52433920

 js= 52433920

no= 20480
sum= 209725440,
 xs= 209725440

 js= 209725440

no= 40960
sum= 838881280,
 xs= 838881280

 js= 838881280

no= 81920
sum= -939483136,
 xs= 3355484160

 js= -939483136

no= 163840
sum= 536952832,
 xs= 13421854720

 js= 536952832

no= 327680
sum= -2147319808,
 xs= 53687255040

 js= -2147319808

no= 655360
sum= 327680,
 xs= 214748692480

 js= 327680

no= 1310720
sum= 655360,
 xs= 858994114560

 js= 655360

no= 2621440
sum= 1310720,
 xs= 3435975147520

 js= 1310720

no= 5242880
sum= 2621440,
 xs= 13743897968640

 js= 2621440

no= 10485760
sum= 5242880,
 xs= 54975586631680

 js= 5242880

no= 20971520
sum= 10485760,
 xs= 219902336040960

 js= 10485760

no= 41943040
sum= 20971520,
 xs= 879609323192320

 js= 20971520

no= 83886080
sum= 41943040,
 xs= 3518437250826240

 js= 41943040

no= 167772160
sum= 83886080,
 xs= 14073748919418880

 js= 83886080

no= 335544320
sum= 167772160,
 xs= 56294995509903360

 js= 167772160

no= 671088640
sum= 335544320,
 xs= 225179981704069120

 js= 335544320

no= 1342177280
sum= 671088640,
 xs= 900719926145187840

 js= 671088640
Press any key to continue

#endif
// ----------------------------------------------

#include <stdio.h>
#include <math.h>
#include <process.h>
#include <conio.h>

#include "sj-01.h"
// ----------------------------------------------

// for time1(), time2()
int main()
{
int no, sum, i, js;
double xs;
no= 10;
while (no > 0) {
sum= 0;
for (i=1;i<=no;i++) {
sum+= i;
}
xs= (1.0 + no)*(no - 1.0 + 1.0)/2.0;
skip(1);
printf("no= %d \n", no);
printf("sum= %d, \n xs= %.0lf \n", sum, xs);
xs= fmod(xs, pow(2, 32));
if (xs > ((pow(2, 31)) - 1)) {
xs-= pow(2, 32);
}
js= (int) xs;
if (js != sum) {
skip(3);
printf("*** error of js <> sum, \n");
pause();
}
// ------------------------------------------------
printf("\n js= %d \n", js);
// pause();
no*= 2;
}
return(0);
}// end of main()