Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // div.cpp : Defines the entry point for the console application.
- //
- #include <stdio.h>
- int div_(int n, int d);
- void binary_out(int b,char *s);
- int main(void)
- {
- int n,d,r;
- for(;;)
- {
- printf("Enter numerator and denominator (-1 to quit):");
- scanf("%d %d",&n,&d);
- if((n==-1)||(d==-1))
- break;
- binary_out(n,"<- numerator\n");
- binary_out(d,"<- denominator\n");
- r=div_(n,d);
- printf("===\n");
- binary_out(r,"<- quotient\n");
- }
- return 0;
- }
- void binary_out(int b,char *s)
- {
- int x;
- for(x=(sizeof(b)<<3)-1;x>=0;x--)
- if(b&(1<<x))
- printf("1");
- else
- printf("0");
- printf("(%d) %s",b,s);
- }
- #define DEBUG_DIV
- int div_(int n, int d)
- {
- int res,x,t;
- res=0; /* зануляем все разряды */
- for(x=(sizeof(n)<<3)-1;x>=0;x--)/* пройти по всем битам от старшего до младшего */
- {
- t=n>>x;/* сдвигаем, чтобы остались только старшие (sizeof(n)-x) бит */
- #ifdef DEBUG_DIV
- printf("************************************************\n");
- binary_out(x," <- x\n");
- binary_out(t," <- t\n\n");
- #endif
- if(t>=d)/* если старшие биты больше делителя */
- {
- #ifdef DEBUG_DIV
- binary_out(n,"_<- n before\n");
- binary_out(d<<x," <- subtrahend\n");
- #endif
- n=n-(d<<x); /* то вычитаем из исходного числа делитель, сдвинутый
- так, чтобы он был под старшими разрядами */
- #ifdef DEBUG_DIV
- printf("--------------------------------\n");
- binary_out(n,"<- difference\n\n");
- binary_out(res," <- old res\n");
- binary_out(1<<x,"+ <- adding\n");
- printf("--------------------------------\n");
- #endif
- res=res+(1<<x); /* а в результат добавляем единичку в соотетствующем разряде */
- #ifdef DEBUG_DIV
- binary_out(res,"<- new res\n");
- #endif
- }
- /* ну а если условие не выполняется, то ничего не делаем
- потому что вычитать нечего, а надо записать в очередной разряд
- нолик... но он уже там!*/
- }
- return res;
- }
- /* clear division -- without debug or comments
- int div_(int n, int d)
- {
- int res,x,t;
- res=0;
- for(x=(sizeof(n)<<3)-1;x>=0;x--)
- {
- t=n>>x;
- if(t>=d)
- {
- n=n-(d<<x);
- res=res+(1<<x);
- }
- }
- return res;
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement