如何在Arduino或C中将十进制数的整数和小数部分作为两个整数?

时间:2013-03-13 13:41:46

标签: c integer arduino

如何将30.8365146转换为两个整数,例如30和8365146,在Arduino或C?

当我尝试通过GPS系列1发送不允许传输分数的XBee数据时,我遇到了这个问题,所以我决定将数据分成两部分。我怎么能这样做?

我尝试过这样的事情:

double num=30.233;
int a,b;

a = floor(num); 
b = (num-a) * pow(10,3);

输出为30232!输出不是30和233.为什么以及如何解决它?

6 个答案:

答案 0 :(得分:3)

double value = 30.8365146;
int left_part, right_part;
char buffer[50];
sprintf(buffer, "%lf", value);
sscanf(buffer, "%d.%d", &left_part, &right_part);

您将左/右部分分别存储为整数。

P.S。另一个解决方案是将你的数字乘以10的幂,并以整数形式发送。

答案 1 :(得分:2)

您可以使用sprintf将整数输出到char数组,然后用空格替换'.'并使用sscanf读回两个整数。

答案 2 :(得分:1)

我为浮动做了,使用double作为临时:

int fract(float raw) {

    static int digits = std::numeric_limits<double>::digits10 - std::numeric_limits<float>::digits10 - 1;
    float intpart;
    double fract = static_cast<double>(modf(raw, &intpart));
    fract = fract*pow(10, digits - 1);
    return floor(fract);
}

我想你可以使用四倍精度浮点格式来实现双倍的同步:libquadmath

答案 3 :(得分:0)

可以通过向下舍入(math.h中的floor(x))来提取30。

小数点后面的数字有点棘手,因为这个数字很可能在内部存储为二进制数,这可能无法很好地转换为您正在寻找的数字,特别是如果涉及浮点数学。你最好的选择可能是将数字转换为字符串,然后从该字符串中提取数据。

答案 4 :(得分:0)

在评论中,您需要跟踪小数位。你不能直接转换为整数。一些代码会做这样的事情:

#include <stdio.h>
#include <math.h>

#define PLACES 3

void extract(double x)
{
        char buf[PLACES+10];
        int a, b;

        sprintf(buf, "%.*f", PLACES, x);
        sscanf(buf, "%d.%d", &a, &b);

        int n = (int) pow(10, PLACES);

        printf("Number           : %.*f\n", PLACES, x);
        printf("  Integer        : %d\n", a);
        printf("  Fractional part: %d over %d\n", b, n);
}

int main()
{
        extract(1.1128);
        extract(20.0);
        extract(300.000512);
}

产地:

Number           : 1.113
  Integer        : 1
  Fractional part: 113 over 1000
Number           : 20.000
  Integer        : 20
  Fractional part: 0 over 1000
Number           : 300.001
  Integer        : 300
  Fractional part: 1 over 1000

答案 5 :(得分:0)

如何使用floor()来获取整数值和 num%1(模运算)得到小数分量?

然后你可以将十进制分量乘以10的倍数并舍入。 这也可以让你控制你发送的小数位数,如果你的通讯有限。标准。

那会有用吗?

#include <math.h>

integer_part = floor(num); 
decimal_part = fmod(num,1)*10^whatever;