Juan Pablo Sada Myt
Juan Pablo Sada Myt

Reputation: 3

How to divide integers and get a float in C

I'm building a paragraph difficulty labeler by getting the number of words, sentences and letters.... I'm trying to divide to integers and get a float for example ((letter_counter / word_counter) * 100); Dividing (80 / 21) * 100 is returning 400 instead of 380.9523, What am I doing wrong? Appreciate some help! Here is an example of my code! letter_counter, word_counter, sentence_counter = int


    // Putting all together
    float L = ((letter_counter / word_counter) * 100);
    printf("The L value = %f\n", L);

    float S = ((float) sentence_counter / word_counter) * 100;
    printf("The S value = %f\n", S);

    int index = round(0.0588 * L - 0.296 * S - 15.8);
    printf("Grade %i\n", index);

    if (index < 1)
    {
        printf("Before Grade 1\n");
    }
    else if (index >= 16)
    {
        printf("Grade 16+\n");
    }
    else
    {
        printf("Grade %i\n", index);
    }

Upvotes: 0

Views: 1885

Answers (2)

Rohan Bari
Rohan Bari

Reputation: 7726

You could put 100.00 rather than 100 to tell the compiler to evaluate the expression as a floating point expression as follows:

int num1 = 80;
int num2 = 21;
float L = (num1 * 100.00) / num2; // 100 -> 100.00

It'll result:

380.952393

Upvotes: 2

Fiddling Bits
Fiddling Bits

Reputation: 8861

You have to cast one of the ints to a float. For example:

float L = (((float)letter_counter / word_counter) * 100);

Upvotes: 6

Related Questions