在没有内置函数的情况下舍入C中的Float值

时间:2017-03-19 10:46:31

标签: c microcontroller pic

我正在用C语言编写PIC单片机的代码。我的浮点值超过4位小数。我想将它舍入到小数点后1位。

但问题是,我不能使用C语言提供的round,floor,ceil函数。

有没有其他方法可以用数学方法做到这一点?

更新1:

我想在连接到PIC单片机的LCD上显示温度。我模拟温度传感器在-40 * C到50 * C的范围内线性提供0-5V。

为此,我使用线性插值来确定温度。值显示在LCD上。这是我的功能:

float Temp;
void Read_Temp()
{
  ADCON0 &= 0xC5;              //Clearing channel selection bits
  ADCON0 |= 0<<3;              //Setting channel 0 selection bits
  __delay_ms(2);               
  while(GO_nDONE);             
  unsigned int adc_value = ((ADRESH<<8)+ADRESL);

  Temp = (adc_value * (90.0/1023.0)) - 40.0; // to show in celcius

  if(TempMode == 'F')  // to show in farenheit
      Temp = (Temp*1.8)+32;    
}

我正在使用一个库来连接lcd。显示浮点值的函数在头文件中将此注释写在其中:

/* LCD_display_float: Displays a floating point numerical value on the LCD 
 * This function take the parameter 'value' and displays it to the number of
 * decimal places specified by the parameter 'dplaces'. NOTE: The function
 * is limited to displaying 4 significant figures due to headroom limitations
 * of the 24 bit float type in MPLAB X. Attempting to display more than 4
 * significant figures will lead to the string "ERR" being displayed. */

void LCD_display_float (float value, unsigned char dplaces); 

因此,当我模拟我的代码时,ERR写在lcd上。我该如何解决这个问题?

如果你们需要lcd_display_float()的定义,我也可以上传它。

2 个答案:

答案 0 :(得分:2)

微控制器的通常解决方案是这样做。小数位用于人类,这种奢侈品不属于嵌入式硬件。哎呀,即使是二进制浮点也有点奢侈。

您可能会看到十进制数学的唯一地方是I / O操作。对于这些情况,内部使用整数最简单。因此范围0.0 - 6553.5在内部表示为0-65535。在输出时,您只需打印value/10 . value%10

答案 1 :(得分:1)

执行此操作的标准方法是缩放,添加0.5,截断和取消缩放:

float x;

...

x *= 10;
x = (int)(x + 0.5);
x /= 10;

或者,在一行中:

x = (int)(x * 10 + 0.5) / 10.;

通过在截断到int之前添加0.5,可以排列小数部分大于0.5的数字。

但还有两点需要考虑:

  1. 这个简单的基本舍入方法将正确处理负数。

  2. 大多数计算机上的浮点数不能完全表示小数部分。因此,您没有真正舍入x到#34;一个小数点后的位置&#34;。如果您稍后打印x,您通常会发现它似乎包含一个数字,例如3.199999而不是3.2。你无能为力;通常的解决方案是在打印出数字时使用像%.1f这样的printf格式。一旦您使用了%.1f这样的printf格式,它就会为您完成所有舍入,因此您不必这样做。

  3. 所以问题是,你实际上用你的浮点数做了什么,他们必须四舍五入到#34;一个小数点后面的位置&#34;?您是将它们打印成字符串,还是用它们做其他事情?如果您要将它们打印出来,您使用的是printf还是其他什么东西?

相关问题