简体   繁体   中英

printf signed integer and decimal point, issue with negative sign

dsPIC33, XC16 compiler.

The dat1 is signed INT16, where it has value of 16434 and -16434 to be printed to 164.34 and -164.34.

printf("---: +/-180 from North   %d.%02d (deg)\n",(dat1/100),(dat1%100));

With dat1=164.34, I get

---: +/-180 from North -164.34 (deg)

With dat1=-164.34, I get

---: +/-180 from North -164.-34 (deg)

==> How to get rid of minus sign on '-.34'?

Your statement is almost correct, except you want to get rid off the sign in the second number. You can use this statement.

printf("---: +/-180 from North   %d.%02d (deg)\n", dat1/100, abs(dat1)%100);

Edit: Thanks to @chux.

The code above works in the desired range from -180.00 to 180.0 degrees. When you need a more general approach you should move the modulo operation before calling abs() .

Postponing the abs() avoids problems at INT_MIN since abs(INT_MIN) may give unexpected results. Then the code should be:

printf("---: +/-180 from North   %d.%02d (deg)\n", dat1 / 100, abs(dat1 % 100));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM