Search code examples
cfloating-pointintegerdecimalcontiki

how to divide two intengers and get a result with decimal numbers?


I'm doing a project in Contiki to a Zolertia module where I need to calculate the risk of a wildfire to occur.

To calculate this risk the formula used is Risk = Temperature / Humidity.
The result of Risk it's a decimal value and there are 5 different values range to classify this Risk: 0-0.49 , 0.5-0.99, 1-1.49, 1.5-1.99, >=2.

My problem is that I can't get decimal results. When I run it in the terminal it shows the value of Temperature and the value of Humidity but just a blank space in the value of Risk.

My code is:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "contiki.h"
#include <float.h>

PROCESS(temp_hum_fog, "Wildfire Control");
AUTOSTART_PROCESSES(&temp_hum_fog);

static struct etimer et;

PROCESS_THREAD(temp_hum_fog, ev, data)
{
    
    int16_t temp, hum;
    float risk;

    PROCESS_BEGIN()


    while(1) {
        etimer_set(&et, CLOCK_SECOND);
        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

        temp = rand() % 45;
        hum = rand() % (85-5)+5;
        risk = (float)temp/(float)hum;

        printf("Temperature:%d ºC\nHumidity:%d HR\nRisk:%f\n", temp,hum,risk);

    }

    PROCESS_END();


}

If I change the type of temp and hum to float it won't show any results also so I'm not sure if float works in Contiki.

Does someone know any solution?


Solution

  • The C implementation you are using is not a full standard C implementation and does not support floating-point conversions in printf. Three options are:

    • Check the documentation for your C implementation to see if support for floating-point can be enabled.
    • Find another C implementation to use (particularly the standard C library).
    • Use integer arithmetic, as in the example below, to do calculations.

    This code will print the quotient to two decimal places, rounded down, using only integer arithmetic:

        int integer  = temp/hum;
        int fraction = temp%hum * 100 / hum;
        printf("Risk: %d.%02d\n", integer, fraction);
    

    Note this assumes the values involved are positive; negative numbers could cause undesired outputs.