oldbutnew
oldbutnew

Reputation: 145

Whats wrong with my math?

I have a function that involves floats and ints. When I run the code, the result comes out wrong. When I enter 4.3 for the input_voltage, I get 3803 for the decimal and EDB for HEX. The correct answer should be 3808 and EE0. Can anyone tell me what might be going on?

#include <stdio.h>

int digital_encoding(float voltage);

int main()
{
    float input_voltage;
    int valid, ch;

    do{
        printf("Please enter the input voltage between 0 and 5 volts: \n");
        valid = scanf("%f", &input_voltage);
        if(input_voltage <= 0){
            printf("Enter a number larger than 0! \n");
            valid = 0;
        }
        if(input_voltage >= 5){
            printf("Enter a number less than 5! \n");
            valid = 0;
        }
    }while(valid != 1);

    digital_encoding(input_voltage);
}
int digital_encoding(float voltage)
{
    int dig_encode;
    dig_encode = ((voltage + 5)*(4095/10));
    printf("The digital encoding equals %d in decimal, and %X in HEX.\n", dig_encode, dig_encode);
    return dig_encode;
}

Upvotes: 0

Views: 149

Answers (5)

Egalitarian
Egalitarian

Reputation: 2218

The problem lies here :

int digital_encoding(float voltage)
{
    **int** dig_encode;
    dig_encode = ((voltage + 5)*(4095/10));
    printf("The digital encoding equals %d in decimal, and %X in HEX.\n", dig_encode,    dig_encode);
    return dig_encode;
}

Use this instead

int digital_encoding(float voltage)
{
    float dig_encode;
    dig_encode = ((voltage + 5)*(4095.00/10));
    printf("The digital encoding equals %d in decimal, and %X in HEX.\n", (int)dig_encode, (int)dig_encode);
    return (int)dig_encode;
}

Upvotes: 1

EvAlex
EvAlex

Reputation: 2938

Result of 4095/10 is int, so it's 409, not 409.5. This is because both numbers are int. To make result float you can write it like this 4095.0/10

Upvotes: 0

Priyank Bhatnagar
Priyank Bhatnagar

Reputation: 814

Problem is here :

 int dig_encode;
        dig_encode = ((voltage + 5)*(4095/10));

Calculate the result in float and then cast it in int before using it.

dig_encode = (int)((voltage + 5)*(4095/10.0));

Upvotes: 1

tpascale
tpascale

Reputation: 2576

I think you may need to change (4095/10) to (4095.0/10) else you'll get integer arithmetic on that ratio with the remainder discarded.

Upvotes: 1

amit
amit

Reputation: 178411

4095/10 is 409 and not 409.5, this is integer arithmetics, so it is rounded down.

You are probably looking for 4095.0 / 10 [or simply 409.5]

Upvotes: 6

Related Questions