| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | possible floating point error in BC |
Hi Peter
PL> I'm in high school and I recently competed in a national
PL> (In Australia) programming competition through my school. I got 4
PL> of the 5 questions done (in the 2 hours). But one of the questions
PL> involved reciprocal numbers. You had to write a program to locate
PL> the numbers between 101 and 999 for which the reciprocal contains
PL> the digit set 1996 and determine the position at which the set
PL> begins. The question also stated that the program should be able to
PL> handle numbers to 500 decimal places.
That's the clue - 500 digits. You're not going to get real numbers
that big in your program without a specialist add-on library.
Therefore, they want you to think laterally. If you can't get a 500
digit answer from your program, or even from your calculator, how
else is there to do it? By hand, of course. You could whip out a
500 digit reciprocal of 326 using paper and long division in about
an hour, using a calculator for the simple multiply and subtract
operations on 4 digit (max) numbers. So let's do the same thing in
a program:
divide 326 into 1 - no go? first digit of answer = 0, multiply 1
by 10.
divide 326 into 10 - no go? 2nd digit of answer = 0, multiply 10
by 10.
divide 326 into 100 - no go? 3rd digit of answer = 0, multiply 100
by 10.
divide 326 into 1000 - goes 3 times. 4th digit of answer is 3.
Subtract 3*326 from 1000 to get 22, multiply it by 10 to get 220.
divide 326 into 220
Since we can't store the digits in a number answer (we don't have
numbers big enough), we'll store them in a string. They're coming
out one by one, it should be easy. Just note that the 1st digit of
the answer is to the *left* of the decimal, eg when finding the
reciprocal of 1, the 1st answer is 1. That's why I refer to ans+1 a
couple of times below.
Note that we're doing all this with integers - there isn't a
floating point number anywhere.
/*-------------------*/
/* PLACES could go up to nearly 65536 under Dos */
#define PLACES 501
#include
#include
#include
int main(void)
{
long i,j,top;
int place, splace;
char ans[PLACES+1],
buf[40],
*found;
char *seek = "1996";
for(i=101; i<=999; i++)
{
top = 1;
for(place=0; place * Origin: Silicon Heaven (3:711/934.16)SEEN-BY: 711/808 934 @PATH: 711/934 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.