Re: Linux printf funny



Op Tue, 27 Feb 2007 14:22:24 +0100 schreef Paul Burke <trash@xxxxxxxxxx>:
Stef wrote:
It does not sound like a windows/linux problem, but more like a
programming error. So please show us the code.


#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>

#include "WinTypes.h"
#include "ftd2xx.h"
#include "ADC.h"

int TareWeight = 0; // ADC reading at no- load
double ScaleFactor = 1.0; // Bridge scale factor

double ReadWeight(void)
{
char buff[100];
double fweight; // Float version of weight
int Weight; // Weight as returned by ADC

Weight= ADCConvert();

fweight= (double)(Weight - TareWeight) * ScaleFactor;
sprintf( buff, "%08x - %08x -> %9.3f", Weight, TareWeight, fweight);
MessageBox( 0,buff,"Conversion Result",0);
return fweight;
}



MessageBox() is just a function that displays the strings supplied, and is in fact a replacement for the Windows message box as in the program's earlier incarnation as a windows GUI program before it got converted to console (don't ask!).

Here's the [modified] console output:

000087bf - 000087bf -> 0.000
000087bf - 000087bf -> 0.000
000087bf - 000087bf -> 0.000
000087bf - 000087bf -> 0.000
000087c0 - 000087bf -> 1.000
000087bf - 000087bf -> 0.000
000087c0 - 000087bf -> 1.000
000087bf - 000087bf -> nan
000087c0 - 000087bf -> nan
000087bf - 000087bf -> nan

"nan" then remains sticky until I restart the program. You'll notice that the int readings are much the same as when the output is correct!

Looks like an optimization problem. The compiler is seeing a constant where it shouldn't, and/or has modified the type of a variable to double.. Without seeing the code that deals with TareWeight, I'd guess this is it.. Try making it volatile.

Another possibility is a bug that modifies ScaleFactor, which BTW isn't declared const.

I know I found some errors in old DOS (turbo C) test programs when I
ported them to new versions of compilers (windows or linux). These
programs worked normally using the old compiler but failed using a
newer one. All the errors where my own (beginners)fault: uninitialized
vars, wrong format specifiers, near/far pointer stuff etc.

I could believe that better if it didn't work for the first few readings.

Floating point types have the property that they can 'saturate' to NaN's, Infinities or Zeroes over successive calculations. Some compilers have a "strict math(s)" option to reduce that effect.



--
Gemaakt met Opera's revolutionaire e-mailprogramma: http://www.opera.com/mail/
.



Relevant Pages

  • Re: CWnd::MessageBoxA does not take 4 parameters
    ... of the messagebox. ... >> This was a cloning process but the original source code seemed to ...
    (microsoft.public.vc.language)
  • Re: Problem with MessageBox
    ... with the compiler. ... > I think the problem is that you are showing the MessageBox from ... > Form_Load instead of in LoadSettings. ...
    (microsoft.public.dotnet.languages.csharp)