delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/04/29/09:38:40

From: David Jenkins <me AT jenkinsdavid DOT demon DOT co DOT uk>
Newsgroups: comp.os.msdos.djgpp
Subject: Floating point bug???
Date: Tue, 29 Apr 1997 03:03:16 +0100
Organization: None
Distribution: world
Message-ID: <qb2z7BAkbVZzEwJA@jenkinsdavid.demon.co.uk>
NNTP-Posting-Host: jenkinsdavid.demon.co.uk
MIME-Version: 1.0
Lines: 61
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp


I'm having some trouble with comparing floats to integers.
The following source uses an integer target variable and a floating
point current variable.
I set the target to a random value the change the value of current
depending on whether it is lower or higher than the target variable.

It seems simple a enough thing to ask my program to do. BUT it won't,
when it reaches "target" weird things happen. The "current" stays an
offset according to SPEED away from the "target".
I've even tried changing the "target" to a float.
Is there some function in C that I don't know about, I'm only a couple
of months old. ;-)


#include <stdio.h>
#include <math.h>
#include <time.h>

#define SPEED 0.1

int             main()
{
    int             target = 0,
                    d,
                    delay1,
                    delay2;
    float           current = 0.0;

/* My system normally sets target to 37 FYI ;-) */
    target = rand() % 100;

    for (d = 0; d < 600; d++) {

        if (current < target)
            current += SPEED;
        if (current > target)
            current -= SPEED;
        if (current == target)
            target = rand() % 100;


        printf("Current = %3.3f  Target = %d\n", current, target);


/*
Just a simple delay I hacked to slow the output.
YOU might want to alter this, or remove it.
*/
        delay1 = uclock();
        for (delay2 = delay1; uclock() < delay1 + 20000; delay2++) {
        }


    }
    return (0);

-- 
http://www.jenkinsdavid.demon.co.uk for Newbie C programmers and a larf. ;-)
David Jenkins

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019