The MASM Forum

General => The Campus => Topic started by: jimg on April 07, 2020, 03:42:28 AM

Title: print real4
Post by: jimg on April 07, 2020, 03:42:28 AM
I'm having a senior moment here, and can't remember or find the rules for printing real numbers.  In the following program, printing a real8 works without problems, but printing a real4 gives a nonsensical number.


include \masm32\include\masm32rt.inc
.data
align 8
pc81 real8 123.e-10
pc41 real4 123.e-10
qfmt db "%g",0
q2fmt db "%f",0
.data?
qbuf db 200 dup (?)
.code
program:

invoke crt_sprintf,addr qbuf,addr qfmt,pc81
print addr qbuf,13,10
invoke crt_sprintf,addr qbuf,addr qfmt,pc41
print addr qbuf,13,10
invoke crt_sprintf,addr qbuf,addr qfmt,real4 ptr pc41
print addr qbuf,13,10
invoke crt_sprintf,addr qbuf,addr q2fmt,pc41
print addr qbuf,13,10
invoke crt_sprintf,addr qbuf,addr q2fmt,real4 ptr pc41
print addr qbuf,13,10

inkey "Press any key to exit..."
invoke ExitProcess,0   
end program
Title: Re: print real4
Post by: jj2007 on April 07, 2020, 04:17:59 AM
QuoteThere is no way to get printf to accept a float, only double or long double. (https://stackoverflow.com/questions/37082784/how-to-print-a-single-precision-float-with-printf)

In case you really need it...
include \masm32\MasmBasic\MasmBasic.inc
.code
MySingle REAL4 123.456
MyDouble REAL8 123.456
start:
  Print Str$("Single: %f\n", MySingle)
  Print Str$("Double: %f\n", MyDouble)
  exit
end start


Output:
Single: 123.4560
Double: 123.4560
Title: Re: print real4
Post by: jimg on April 07, 2020, 04:38:56 AM
That must not have been the link you meant to post.  I've been looking for several hours and didn't find anything that made any sense as to why sprintf prints incorrectly.  It doesn't work for real10 either, only real8.  You'd think they would be more clear on that at the microsoft site, but I couldn't find any official microsoft  words of wisdom.  The easy answer is fld pc4real   fstp pc8real, and print that.  I just wanted to make sure I wasn't doing something stupid.
Title: Re: print real4
Post by: HSE on April 07, 2020, 04:57:35 AM
real4$ and real10$ are in macros.asm from ages  :biggrin:
Title: Re: print real4
Post by: aw27 on April 07, 2020, 05:44:48 PM
floats need to be promoted to double when using printf (and others based on vfprintf). This is exactly what the C standards say.