我在Contiki3.0中使用了RPL,我需要做一些计算,结果是浮动的。但是,它不是给我浮动的结果,它只是计算整数--例如: 5/2 = 2.0,而不是2.5。我怎么才能得到正确的答案?我无法在Contiki3.0中打印float或double,所以我使用这段代码将float转换为一个字符串:
// Reverses a string 'str' of length 'len'
void reverse(char* str, int len)
{
int i = 0, j = len - 1, temp;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
// Converts a given integer x to string str[].
// d is the number of digits required in the output.
// If d is more than the number of digits in x,
// then 0s are added at the beginning.
int intToStr(int x, char str[], int d)
{
int i = 0;
while (x) {
str[i++] = (x % 10) + '0';
x = x / 10;
}
// If number of digits required is more, then
// add 0s at the beginning
while (i < d)
str[i++] = '0';
reverse(str, i);
str[i] = '\0';
return i;
}
// Converts a floating-point/double number to a string.
void ftoa(float n, char* res, int afterpoint)
{
// Extract integer part
int ipart = (int)n;
// Extract floating part
float fpart = n - (float)ipart;
// convert integer part to string
int i = intToStr(ipart, res, 0);
// check for display option after point
if (afterpoint != 0) {
res[i] = '.'; // add dot
// Get the value of fraction part upto given no.
// of points after dot. The third parameter
// is needed to handle cases like 233.007
fpart = fpart * powf(10, afterpoint);
intToStr((int)fpart, res + i + 1, afterpoint);
}
}谢谢你的帮助谢谢哈宁
发布于 2021-03-30 14:40:16
如果要将数字打印为浮点数,只需将浮点之前的部分打印为整数,打印点,然后以10的幂将浮点后的部分乘以,然后将其打印为另一个整数。例如,如果要在浮点数之后打印6位数字,请将小数部分乘以1000000。
首先需要一个单独的缓冲区来打印浮点后的部分--第一个数字必须是非零,因此安全选项用另一个数字(例如"1“)填充,而您没有打印。要做到这一点,只需将1.0添加到小数部分,然后再乘以它。
以下是完整的代码:
float f = 5.0 / 2;
char fractional_part[10];
sprintf(fractional_part, "%d", (int)((f - (int)f + 1.0) * 1000000));
printf("%d.%s\n", (int)f, &fractional_part[1]); // prints "2.500000"发布于 2021-03-30 13:50:30
因为5/2是整数除法的一种形式,所以您输入的是什么,这意味着如果输入5/2,你只会得到一个整数返回,形式是2。
要解决这个问题,让您的5/2是5/2.0,以便将其作为浮点数读取,这将确保您将得到一个浮点小数点的答案。
发布于 2021-06-16 08:05:53
我还想在cooja中打印浮点值,所以我找到了这个解决方案。
// digits before point
unsigned short d1(float f){
return((unsigned short)f);
}
// digits after point
unsigned short d2(float f){
return(1000*(f-d1(f)));
}
int main()
{
float max = 6.796;
printf("max value %u.%u \n", d1(max) , d2(max));
}https://stackoverflow.com/questions/66872070
复制相似问题