Article View: comp.lang.c.moderated
Article #2071Re: Please help me elect rounding of int division
From: Carl Jacobson
Date: Sun, 25 Feb 1996 18:00
Date: Sun, 25 Feb 1996 18:00
56 lines
2363 bytes
2363 bytes
xmsb@shadow.borland.com (Maurice S. Barnum) wrote:
>swedecj@vcnet.com (Carl Jacobson) writes:
>>Please help me solve this task.
>>I have now tried (Borland C++ version 3.0) for two solid days to write
>>a function that would allow me to round the quotient of (a/b) up or
>>down based on the "nearest" integer instead of being truncated to the
>>smallest. If exactly half way, return the "odd."
> post what you have written so far.
> --xmsb
It took a long time for my article to get posted, sooo I finally wrote
the function as follows. It may be the long way around the barn, but
it works OK. I'm sure there are much better ways to handle the
quation.
long div_numbers(long a, long b) /* function header */
{
long q=0;
int neg=0;
if (a<0 && b<0) { /* account for negative integers */
a=abs(a); /* by making them positive in */
b=abs(b); /* support of proper rounding */
neg=0;;
}
if (a<0 || b<0) {
a=abs(a);
b=abs(b);
neg=1;
}
q=a/b; /* find quotient */
if (((a%b)*100)>(b*50)) /* proper rounding routine */
q++;
if (((a%b)*100)==(b*50)&&(q%2==0))
q++;
if (neg==1) q=-q; /* flip back to neg quotient */
/* if required */
return(q);
}
Thank you for your attention.
Carl J.
---------------------------------------------------------------
Carl Jacobson swedecj@vcnet.com
P.O. Box 3607 Phone: US 805.523.1724
Thousand Oaks, CA 91359 Fax : US 805.523.1454
Technical Details
Message-ID:
<4gq83r$omb@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4gfaif$1tt@solutions.solon.com> <4ggf1m$8rb@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: swedecj@vcnet.com (Carl Jacobson) Newsgroups: comp.lang.c.moderated,comp.lang.c Subject: Re: Please help me elect rounding of int division Date: 25 Feb 1996 12:00:27 -0600 Organization: Internet Access of Ventura County 805.383.3500 Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4gq83r$omb@solutions.solon.com> References: <4gfaif$1tt@solutions.solon.com> <4ggf1m$8rb@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com X-Newsreader: Forte Free Agent 1.0.82