PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 8, 2022

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

 August 08, 2022     c, contiki, decimal, floating-point, integer     No comments   

Issue

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.



Answered By - Eric Postpischil
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing