简体   繁体   English

printf带符号的整数和小数点,带有负号的问题

[英]printf signed integer and decimal point, issue with negative sign

dsPIC33, XC16 compiler. dsPIC33,XC16编译器。

The dat1 is signed INT16, where it has value of 16434 and -16434 to be printed to 164.34 and -164.34. dat1的符号为INT16,其值16434和-16434要打印到164.34和-164.34。

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

With dat1=164.34, I get 随着dat1 = 164.34,我得到

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

With dat1=-164.34, I get 随着dat1 = -164.34,我得到

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

==> How to get rid of minus sign on '-.34'? ==>如何摆脱'-.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. 编辑: 感谢@chux。

The code above works in the desired range from -180.00 to 180.0 degrees. 上面的代码在-180.00至180.0度的期望范围内工作。 When you need a more general approach you should move the modulo operation before calling abs() . 如果需要更通用的方法,则应在调用abs()之前移动模运算。

Postponing the abs() avoids problems at INT_MIN since abs(INT_MIN) may give unexpected results. 延迟abs()可以避免INT_MIN出现问题,因为abs(INT_MIN)可能会产生意外的结果。 Then the code should be: 然后代码应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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