-
Notifications
You must be signed in to change notification settings - Fork 0
/
iadf.c
733 lines (732 loc) · 26.3 KB
/
iadf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*==========================================================*/
/* Модуль операций с десятичными дробями, представленными */
/* в формате заданной разрядности с естественным положением */
/* десятичной запятой. */
/* Файл реализации iadf.c */
/*----------------------------------------------------------*/
/* Автор: Орещенков Игорь Сергеевич, 2019 г. */
/* Язык программирования: Си. */
/* Компилятор: Digital Mars C/C++ Compiler. */
/*==========================================================*/
#include <stdio.h>
#include "iadf.h"
static int iadfAbsAdd (struct IADF* df1, const struct IADF* df2);
static int iadfAbsSub (struct IADF* df1, const struct IADF* df2);
static int iadfAbsMul (struct IADF* df1, const struct IADF* df2);
static int iadfAbsDiv (struct IADF* df1, const struct IADF* df2);
static int iadfAbsDivPrepare (unsigned char* v, int n, const struct IADF* df);
static void iadfAbsDivDebugPrint (const char* s, const unsigned char* v, int n);
static int iadfGetDigit (const struct IADF* df, int i);
static int iadfSetDigit (struct IADF* df, int i, int d);
static int iadfMaxInt (int a, int b);
static int iadfMinInt (int a, int b);
/*=========================================================*/
/* Присваивание значения переменной "десятичная дробь". */
/* Вызов: df - указатель на переменную "десятичная дробь", */
/* s - строка со значением для присваивания, */
/* Возврат: количество обработанных символов в строке s. */
/*=========================================================*/
int iadfInit (struct IADF* df, const char* s)
{
unsigned char v[IADFCAPACITY];
char c;
int sgn; /* знак числа */
int m, n; /* m - количество цифр в целой части, n - общее количество цифр */
int i, j; /* i - индекс по строке, j - индекс по разрядам десятичной дроби */
int dpf, ef; /* dpf - признак наличия дробной части, ef - признак ошибки */
int res;
/* Синтаксический разбор строки. */
m = n = 0;
dpf = ef = 0;
i = j = 0;
/* Определение знака числа. */
sgn = 0; /* предполагается неотрицательное число */
c = *s;
if (c == '-' || c == '+') {
if (c == '-')
sgn = 1;
i++; /* переход к рассмотрению следующих символов в записи числа */
}
/* Обработка десятичных разрядов числа. */
do {
c = *(s + i);
if (c >= '0' && c <= '9') {
/* Обработка цифры. */
if (!dpf) {
/* Обработка разряда целой части. */
if (n > 0 || c > '0') {
v[j++] = c - '0';
n = j;
}
}
else {
/* Обработка разряда дробной части. */
v[j++] = c - '0';
if (c > '0')
/* Фиксация значащего разряда. */
n = j;
}
}
else if (c == '.' || c == ',') {
/* Обработка десятичного разделителя. */
if (!dpf) {
/* Фиксация десятичной запятой */
m = n;
dpf = 1;
}
else
/* Ошибка: десятичный разделитель уже был обработан ранее. */
ef = 2;
}
else if (c)
/* Ошибка: обнаружен недопустимый символ. */
ef = 1;
/* Подготовка к рассмотрению следующего символа строки. */
if (!ef)
i++;
} while (j < IADFCAPACITY && !ef && c);
if (!dpf) {
/* Обработано целое число. */
m = n;
/* После целого числа может идти десятичный разделитель. */
c = *(s + i);
if (c == '.' || c == ',')
i++;
}
res = i;
/* Запись результата обработки во внутреннее представление. */
df->n = n;
df->m = m;
df->s = sgn;
for (i = 0; i < n; i++)
iadfSetDigit (df, i, v[i]);
return res;
}
/*=======================================================================*/
/* Преобразование десятичной дроби из внутреннего представления в строку */
/* в формате отображения на индикаторе калькулятора. */
/* Вызов: df - указатель на переменную "десятичная дробь", */
/* buf - указатель на буфер для формирования строки, */
/* n - размер буфера. */
/* Возврат: 0 - преобразование выполнено успешно, */
/* 1 - ошибка преобразования: недостаточный размер буфера. */
/*=======================================================================*/
int iadfToStr (const struct IADF* df, char* buf, int n)
{
int res = n < df->s + df->n + (df->m > 0? 2: 3);
int i;
if (!res) {
/* Запись знака числа. */
if (df->s)
*(buf++) = '-';
/* Запись разрядов целой части. */
i = 0;
if (df->m == 0)
*(buf++) = '0';
else
while (i < df->m)
*(buf++) = '0' + iadfGetDigit(df, i++);
*(buf++) = ',';
/* Запись разрядов дробной части. */
while (i < df->n)
*(buf++) = '0' + iadfGetDigit (df, i++);
/* Финализация строки. */
*buf = '\0';
}
return res;
}
/*====================================================*/
/* Сложение десятичных дробей. */
/* Вызов: df1 - указатель на первое слагаемое, */
/* df2 - указатель на второе слагаемое. */
/* Возврат: 0 - сумма записана в df1, */
/* 1 - переполнение (df1 * 10^IADFCAPACITY). */
/*====================================================*/
int iadfAdd (struct IADF* df1, const struct IADF* df2)
{
int res, cmp;
struct IADF df0;
if (df1->s != df2->s) {
/* Операнды имеют разные знаки. */
/* Результат принимает знак большего по абсолютной величине операнда */
/* или знак "+", если операнды равны по абсолютной величине. */
/* Абсолютная величина результата определяется вычитанием меньшей абсолютной величины из большей. */
cmp = iadfAbsCompare (df1, df2);
if (cmp == 1) /* |df1| > |df2| */
res = iadfAbsSub (df1, df2);
else if (cmp == -1) { /* |df1| < |df2| */
df0 = *df2;
df0.s = df2->s;
res = iadfAbsSub (&df0, df1);
*df1 = df0;
}
else { /* |df1| == |df2| */
df1->n = df1->m = 0;
df1->s = 0;
res = 0;
}
}
else
/* Операнды имеют одинаковые знаки. */
/* Результат будет того же знака. */
/* Абсолютная величина результата определяется сложением абсолютных величин. */
res = iadfAbsAdd (df1, df2);
return res;
}
/*====================================================*/
/* Вычитание десятичных дробей. */
/* Вызов: df1 - указатель на уменьшаемое, */
/* df2 - указатель на вычитаемое. */
/* Возврат: 0 - разность записана в df1, */
/* 1 - переполнение (df1 * 10^IADFCAPACITY). */
/*====================================================*/
int iadfSub (struct IADF* df1, const struct IADF* df2)
{
int res, cmp;
struct IADF df0;
if (df1->s != df2->s) {
/* Операнды имеют разные знаки. */
/* Результат принимает знак уменьшаемого. */
/* Абсолютная величина результата равна сумме абсолютных величин операндов. */
res = iadfAbsAdd (df1, df2);
}
else {
/* Операнды имеют одинаковые знаки. */
/* Если абсолютная величина уменьшаемого больше абсолютной величины вычитаемого, то */
/* результат принимает знак уменьшаемого. Если абсолютная величина уменьшаемого меньше */
/* абсолютной величины вычитаемого, то результат принимает знак, противоположный знаку */
/* вычитаемого. */
/* Абсолютная величина результата равна абсолютной величине разности абсолютных величин операндов. */
cmp = iadfAbsCompare (df1, df2);
if (cmp == 1) /* |df1| > |df2| */
res = iadfAbsSub (df1, df2);
else if (cmp == -1) { /* |df1| < |df2| */
df0 = *df2;
df0.s = !df2->s;
res = iadfAbsSub (&df0, df1);
*df1 = df0;
}
else { /* |df1| == |df2| */
df1->n = df1->m = 0;
df1->s = 0;
res = 0;
}
}
return res;
}
/*====================================================*/
/* Умножение десятичных дробей. */
/* Вызов: df1 - первый множитель, */
/* df2 - второй множитель. */
/* Возврат: 0 - произведение в df1, */
/* 1 - переполнение (df1 * 10^IADFCAPACITY). */
/*====================================================*/
int iadfMul (struct IADF* df1, const struct IADF* df2)
{
int res;
/* Абсолютная величина произведения равна произведению абсолютных величин. */
res = iadfAbsMul (df1, df2);
/* Знак произведения "+", если знаки множителей совпадают, и "-", если знаки множителей разные. */
df1->s = df1->s != df2->s;
return res;
}
/*====================================================*/
/* Деление десятичных дробей. */
/* Вызов: df1 - делимое, */
/* df2 - делитель. */
/* Возврат: 0 - частное от деления в df1, */
/* 1 - переполнение (df1 * 10^IADFCAPACITY), */
/* 2 - ошибка деления на ноль. */
/*====================================================*/
int iadfDiv (struct IADF* df1, const struct IADF* df2)
{
int res;
/* Абсолютная величина частного равна отношению абсолютных величин. */
res = iadfAbsDiv (df1, df2);
/* Знак частного "+", если знаки операндов совпадают, и "-", если знаки операндов разные. */
df1->s = df1->s != df2->s;
return res;
}
/*====================================================*/
/* Сравнение абсолютных величин десятичных дробей. */
/* Вызов: df1 - указатель на первую десятичную дробь, */
/* df2 - указатель на вторую десятичную дробь. */
/* Возврат: -1: |df1| < |df2|, */
/* 0: |df1| = |df2|, */
/* 1: |df1| > |df2|. */
/*====================================================*/
int iadfAbsCompare (const struct IADF* df1, const struct IADF* df2)
{
int res;
int i, n;
int d1, d2;
/* Сравнение по количеству разрядов в целых частях дробей. */
res = df1->m > df2->m? 1: df1->m < df2->m? -1: 0;
/* Поразрядное сравнение, если целые части содержат одинаковое количество разрядов. */
i = 0; n = df1->n < df2->n? df1->n: df2->n;
while (!res && i < n) {
d1 = iadfGetDigit (df1, i);
d2 = iadfGetDigit (df2, i);
res = d1 > d2? 1: d1 < d2? -1: 0;
i++;
}
/* Если просмотренные разряды равны, то сравнение по общему количеству разрядов. */
if (!res)
res = df1->n > df2->n? 1: df1->n < df2->n? -1: 0;
return res;
}
/*====================================================*/
/* Сложение абсолютных величин десятичных дробей. */
/* Вызов: df1 - указатель на первое слагаемое, */
/* df2 - указатель на второе слагаемое. */
/* Возврат: 0 - результат сложения записан в df1, */
/* 1 - переполнение (df1 * 10^IADFCAPACITY). */
/*====================================================*/
static int iadfAbsAdd (struct IADF* df1, const struct IADF* df2)
{
const int ADCAPACITY = 1 + 2 * IADFCAPACITY;
unsigned char c[ADCAPACITY]; /* разряды суммы */
int res;
int mc, nc; /* характеристики разрядов суммы */
int o1, o2; /* смещения слагаемых относительно суммы */
int d, d1, d2; /* значения разрядов */
int cf; /* признак переноса в старший разряд */
int ic, i, j;
/* df1 [ Целая (m1) часть | Дробная (n1 - m1) часть ] */
/* o1--------> */
/* df2 [ Целая (m2) часть | Дробная (n2 - m2) часть ] */
/* o2-> */
/* c [ | Целая (mc) часть | Дробная (nc - mc) часть ] */
/* ^-- зарезервированный разряд для возможного переноса */
mc = 1 + iadfMaxInt (df1->m, df2->m); /* самый старший разряд зарезервирован для единицы переноса */
nc = mc + iadfMaxInt (df1->n - df1->m, df2->n - df2->m);
/* Вычисление смещений разрядов слагаемых относительно разрядов результата. */
o1 = mc - df1->m;
o2 = mc - df2->m;
/* Цикл определения разрядов суммы. */
cf = 0; /* признак переноса в старший разряд */
ic = nc;
while (ic-- > 0) {
d1 = o1 <= ic && ic < df1->n + o1? iadfGetDigit (df1, ic - o1): 0;
d2 = o2 <= ic && ic < df2->n + o2? iadfGetDigit (df2, ic - o2): 0;
d = d1 + d2 + cf;
if (d > 9) {
c[ic] = d - 10;
cf = 1;
}
else {
c[ic] = d;
cf = 0;
}
}
/* Формирование внутреннего представления результата. */
/* Исключение незначащих разрядов целой части. */
i = 0;
while (i < mc && !c[i])
i++;
mc -= i;
nc -= i;
/* Проверка переполнения разрядной сетки. */
if (mc > IADFCAPACITY) {
mc -= IADFCAPACITY;
res = 1;
}
else
res = 0;
/* Исключение незначащих разрядов дробной части. */
if (nc > IADFCAPACITY)
nc = IADFCAPACITY;
j = i + nc - 1;
while (nc > mc && !c[j]) {
j--;
nc--;
}
/* Копирование значащих разрядов. */
for (ic = i; ic <=j; ic++)
iadfSetDigit (df1, ic - i, c[ic]);
df1->n = nc;
df1->m = mc;
return res;
}
/*======================================================*/
/* Вычитание абсолютных величин десятичных дробей. */
/* Вызов: df1 - указатель на уменьшаемое, */
/* df2 - указатель на вычитаемое. */
/* Возврат: 0 - результат вычитания записан в df1, */
/* 1 - ошибка: вычитаемое больше уменьшаемого. */
/*======================================================*/
static int iadfAbsSub (struct IADF* df1, const struct IADF* df2)
{
const int SBCAPACITY = 2 * IADFCAPACITY;
unsigned char c[SBCAPACITY]; /* разряды разности */
int mc, nc; /* характеристики разрядов разности */
int o1, o2; /* смещения операндов */
int d1, d2; /* цифры операндов */
int cf; /* признак заимствования */
int ic, i, j;
int res;
mc = iadfMaxInt (df1->m, df2->m);
nc = mc + iadfMaxInt (df1->n - df1->m, df2->n - df2->m);
/*-------------------------------------------------------------------------*/
/* df1 [ Целая (m1) часть | Дробная (n1 - m1) часть ]000000 */
/* df2 --- o2 ---> [ Целая (m2) часть | Дробная (n2 - m2) часть ] */
/* c [ Целая (mc) часть | Дробная (nc - mc) часть ] */
/*-------------------------------------------------------------------------*/
/* Вычисление смещений операндов относительно результата. */
o1 = mc - df1->m;
o2 = mc - df2->m;
/* Цикл определения значений разрядов разности. */
cf = 0; /* признак заимствования */
ic = nc;
while (ic-- > 0) {
d1 = ic < o1 || ic >= df1->n + o1? 0: iadfGetDigit (df1, ic - o1);
d2 = ic < o2 || ic >= df2->n + o2? 0: iadfGetDigit (df2, ic - o2);
if (d1 >= d2 + cf) {
c[ic] = d1 - d2 - cf;
cf = 0;
}
else {
c[ic] = 10 + d1 - d2 - cf;
cf = 1;
}
}
/* Оценка результата вычислений. */
res = cf;
/* Формирование внутреннего представления результата. */
if (!res) {
/* Исключение незначащих разрядов целой части. */
i = 0;
while (i < mc && !c[i])
i++;
mc -= i;
nc -= i;
/* Исключение незначащих разрядов дробной части. */
if (nc > IADFCAPACITY)
nc = IADFCAPACITY;
j = i + nc - 1;
while (nc > mc && !c[j]) {
j--;
nc--;
}
/* Копирование значащих разрядов. */
for (ic = i; ic <= j; ic++)
iadfSetDigit (df1, ic - i, c[ic]);
df1->n = nc;
df1->m = mc;
}
return res;
}
/*====================================================*/
/* Перемножение абсолютных величин десятичных дробей. */
/* Вызов: df1 - указатель на первый множитель, */
/* df2 - указатель на второй множитель. */
/* Возврат: 0 - результат умножения записан в df1, */
/* 1 - переполнение (df1 * 10^IADFCAPACITY). */
/*====================================================*/
static int iadfAbsMul (struct IADF* df1, const struct IADF* df2)
{
int res;
const int PRCAPACITY = 1 + 2 * IADFCAPACITY;
unsigned char pr[PRCAPACITY];
int c, d, d1, d2;
int i, j, k;
int p1, p2;
int pm, pnm;
if (!df1->n || !df2->n) {
/* Если один из сомножителей равен нулю, то и произведение равно нулю. */
df1->n = 0;
df1->m = 0;
res = 0;
}
else {
/* Ни один из сомножителей не равен нулю. */
/* Обнуление разрядов результата. */
for (i = 0; i < PRCAPACITY; i++)
pr[i] = 0;
/* Цикл по разрядам первого множителя. */
i = df1->n;
while (i-- > 0) {
d1 = iadfGetDigit (df1, i);
if (!d1)
continue; /* частичное произведение с нулём не влияет на результат */
/* Цикл по разрядам второго множителя. */
j = df2->n;
while (j-- > 0) {
d2 = iadfGetDigit (df2, j);
if (!d2)
continue; /* частичное произведение с нулём не влияет на результат */
/* Прибавление произведения разрядов к накапливаемому результату. */
k = PRCAPACITY - 1 - ((df1->n - (i + 1)) + (df2->n - (j + 1)));
c = d1 * d2;
do {
d = pr[k] + c;
c = d / 10; /* величина переноса в следующий разряд */
d = d % 10; /* новое значение текущего разряда */
pr[k--] = d;
} while (c > 0);
}
}
/* Преобразование результата во внутреннее представление десятичной дроби. */
/* [0000000____pm____|__pnm__00] */
/* ^-p1 p2-^ */
/* p1 - первый значащий разряд произведения, */
/* p2 - разряд, следующий за последним значащим разрядом произведения. */
/* Внимание! Порядок следования следующих трёх блоков важен! */
/* Вычисление количества _всех_ дробных разрядов произведения. */
pnm = (df1->n - df1->m) + (df2->n - df2->m);
/* Вычисление количества _значащих_ целых разрядов произведения. */
p1 = 0;
p2 = PRCAPACITY - pnm;
while (!pr[p1] && p1 < p2)
p1++;
pm = p2 - p1;
/* Проверка на переполнение. */
if (pm > IADFCAPACITY) {
pm -= IADFCAPACITY;
res = 1;
}
else
res = 0;
/* Формирование внутреннего представления. */
/* Уточнение правой границы произведения. */
p2 = p1 + IADFCAPACITY;
if (p2 > PRCAPACITY)
p2 = PRCAPACITY;
while (p2 > p1 + pm && !pr[p2 - 1])
p2--;
/* Перенос разрядов результата. */
j = 0;
for (i = p1; i < p2; i++)
iadfSetDigit (df1, j++, pr[i]);
df1->m = pm;
df1->n = p2 - p1;
}
return res;
}
/*===============================================*/
/* Деление абсолютных величин десятичных дробей. */
/* Вызов: df1 - делимое, */
/* df2 - делитель. */
/* Возврат: 0 - в df1 возвращено частное, */
/* 1 - переполнение, df1 * 10^N, */
/* 2 - ошибка, деление на ноль. */
/*===============================================*/
#define DEBUG 0
static int iadfAbsDiv (struct IADF* df1, const struct IADF* df2)
{
const int DVCAPACITY = 1 + 2 * IADFCAPACITY;
int res;
int na, nb;
int ma, mb;
unsigned char a[DVCAPACITY]; /* рабочие разряды делимого */
unsigned char b[IADFCAPACITY]; /* разряды делителя */
unsigned char c[DVCAPACITY]; /* формируемые разряды частного */
int ia, ib, ic;
int i, j;
int ge, d, cf;
int k; /* показатель степени для коэффициента 10^k, на который следует умножить частное. */
if (!df2->n)
/* Деление на ноль. */
res = 2;
else if (df1->n) {
/* Делимое отлично от нуля (иначе результат уже готов). */
/* Подготовка разрядов делимого и делителя. */
na = iadfAbsDivPrepare (a, DVCAPACITY, df1);
nb = iadfAbsDivPrepare (b, IADFCAPACITY, df2);
/* Определение длины целой части делимого после приведения делителя к целому числу */
/* ma = df1->m + df2->n - df2->m; */
/* с вычетанием образовавшихся ведущих нулевых разрядов в целой части. */
ma = df1->m + (df2->n - df2->m) - (df1->n - na);
#ifdef DEBUG
#if DEBUG==1
printf ("\n");
iadfAbsDivDebugPrint ("a = ", a, DVCAPACITY);
printf ("na = %d\n", na);
iadfAbsDivDebugPrint ("b = ", b, IADFCAPACITY);
printf ("nb = %d\n", nb);
#endif
#endif
/* Вычисление разрядов частного. */
/*----------------------------------------------*/
/* a [ целая (ma) часть | дробная часть ] */
/* ^-- ia */
/* Условие разрядов целой части: ia <= ma - nb. */
/* b [ целая (nb) часть ] */
/* c [ ] */
/* ^-- ic */
/*----------------------------------------------*/
k = ma - nb;
ia = ic = 0;
/* На старте процесса делимое и делитель имеют одинаковое количество разрядов, */
/* однако делимое всё ещё может быть меньше делителя, и тогда потребуется ещё */
/* один сдвиг, который учитывается только в случае, если определяются дробные разряды. */
do {
c[ic] = 0;
do {
/* Поразрядное сравнение делимого и делителя. */
ge = ia? a[ia - 1]:0; /* оценка величины предшествующего разряда делимого */
if (!ge) {
ib = 0;
while (ib < nb && a[ia + ib] == b[ib])
ib++;
ge = !(ib < nb && a[ia + ib] < b[ib]);
}
/* Если делимое больше делителя, то вычитание делителя из делимого. */
if (ge) {
cf = 0; /* признак заимствования из старшего разряда */
ib = nb;
while (ib-- > 0) {
d = a[ia + ib] - b[ib] - cf;
if (d < 0) {
d += 10;
cf = 1;
}
else
cf = 0;
a[ia + ib] = d;
}
if (cf)
a[ia - 1] -= cf; /* заимствование из старшего разряда делимого */
/* Учёт выполненного вычитания в разряде частного. */
c[ic]++;
}
} while (ge);
ia++; /* сдвиг делимого относительно делителя вправо */
if (ic || c[ic])
ic++; /* переход к определению следующего разряда частного */
else
k--; /* первый нулевой разряд отправляется в масштабный коэффициент */
/* Цикл продолжается до тех пор, пока не будет получено нужное количество дробных разрядов, */
/* либо пока получаемые разряды - целые (для уточнения величины переполнения). */
} while (ic < IADFCAPACITY + (k >= 0? 0: k + 1) || ic <= k);
/* Полученный в массиве c результат следует трактовать как (c,cccc * 10^k). */
if (k < IADFCAPACITY)
res = 0; /* деление завершилось без ошибок */
else {
k -= IADFCAPACITY;
res = 1; /* при делении возникло переполнение */
}
/* Формирование внутреннего представления результата. */
df1->m = k >= 0? k + 1: 0; /* количество целых разрядов результата */
i = 0;
/* Запись значащих нулевых разрядов дроби. */
while (k + i < -1)
iadfSetDigit (df1, i++, 0);
/* Запись остальных разрядов дроби (как нулевых, так и не нулевых). */
j = 0;
while (i < IADFCAPACITY)
iadfSetDigit (df1, i++, c[j++]);
df1->n = IADFCAPACITY;
/* Отбрасывание незначащих разрядов дробной части. */
while (df1->n > df1->m && !iadfGetDigit (df1, df1->n - 1))
df1->n--;
}
else
res = 0;
return res;
}
/*===================================================================*/
/* Отладочная печать содержимого массива с рабочими разрядами числа. */
/* Вызов: s - строка с информационным сообщением, */
/* v - массив с рабочими разрядами, */
/* n - количество разрядов в массиве. */
/*===================================================================*/
static void iadfAbsDivDebugPrint (const char* s, const unsigned char* v, int n)
{
int i;
printf ("%s[", s);
for (i = 0; i < n; i++)
printf ("%d", v[i]);
printf ("]\n");
}
/*=============================================================*/
/* Подготовка операнда для операции деления десятичных дробей, */
/* заключающаяся в переносе необходимых разрядов в массив. */
/* Вызов: v - массив для разрядов операнда, */
/* n - размер массива, */
/* df - операнд - десятичная дробь. */
/* Возврат: количество обработанных разрядов. */
/* v - массив, заполненный разрядами операнда. */
/*=============================================================*/
static int iadfAbsDivPrepare (unsigned char* v, int n, const struct IADF* df)
{
register int i, j;
int m;
i = j = 0;
/* Пропуск ведущих нулей. */
while (i < df->n && !iadfGetDigit (df, i))
i++;
/* Копирование разрядов. */
while (i < df->n)
v[j++] = iadfGetDigit (df, i++);
m = j;
/* Дополнение нулями. */
while (j < n)
v[j++] = 0;
return m;
}
/*=======================================================================*/
/* Получение значения десятичного разряда переменной "десятичная дробь". */
/* Вызов: df - указатель на переменную "десятичная дробь", */
/* i - порядковый номер разряда. */
/* Возврат: значение запрошенного разряда. */
/*=======================================================================*/
static int iadfGetDigit (const struct IADF* df, int i)
{
int res;
/* Проверка входных данных. */
if (i < 0 || i >= IADFCAPACITY) {
printf ("DEBUG ERROR: iadfGetDigit () - bad decimal digit index: i = %d.\n", i);
}
else {
res = (int)df->v[i];
}
return res;
}
/*=======================================================================*/
/* Установка значения десятичного разряда переменной "десятичная дробь". */
/* Вызов: df - указатель на переменную "десятичная дробь", */
/* i - порядковый номер разряда, */
/* d - значение от 0 до 9. */
/* Возврат: 1 - значение установлено, */
/* 0 - ошибка установки значения. */
/*=======================================================================*/
static int iadfSetDigit (struct IADF* df, int i, int d)
{
int res;
/* Проверка входных данных. */
if (i < 0 || i >= IADFCAPACITY) {
printf ("DEBUG ERROR: iadfSetDigit () - bad decimal digit index: i = %d.\n", i);
res = 0;
}
else if (d < 0 || d > 9) {
printf ("DEBUG ERROR: iadfSetDigit () - bad decimal digit value: d = %d.\n", d);
res = 0;
}
/* Выполнение установки разряда. */
else {
df->v[i] = (unsigned char)d;
res = 1;
}
return res;
}
/*=============================================*/
/* Определение максимального из двух значений. */
/* Вызов: a - первое значение, */
/* b - второе значение. */
/* Возврат: max (a, b). */
/*=============================================*/
static int iadfMaxInt (int a, int b)
{
return a > b? a: b;
}
/*============================================*/
/* Определение минимального из двух значений. */
/* Вызов: a - первое значение, */
/* b - второе значение. */
/* Возврат: min (a, b). */
/*============================================*/
static int iadfMinInt (int a, int b)
{
return a < b? a: b;
}