user23306917
user23306917

Reputation: 1

value divided by 100 does not return a decimal place although both the divident and the divisor are declared as data type float in c languages

I am about to solve the readability task from the CS50 course. This should become a programm that counts letters and words to use them in the Coleman-Liau -Index. Therefore i would like to divide the return value of the class which counts the letters by 100 . Too see if it works i output the value by printf. For example if i enter the value Whatever, the value 0.08 should be output. But Instead it outputs 0.

I have definied the variable score as float and did the the same with the return value with the return value of the class compute_score. I also definded the divider and the divisor with the same datatype. I have even specified in the placeholder that exactly 2 decimal places should be specified. Unfortunately, I can't think of where the error lies. I would be very happy about help. below you can read the code.

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

float compute_score(string text);

int main(void)
{

    string text = get_string("Text: ");

    float score = compute_score(text);

    printf("%2.f", score);
}
float compute_score(string text)
{

    float divider = 100.00;
    float letter = 0;

    for (int i = 0; i < strlen(text); i++)
    {
        if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
        {
            letter++;
        }

    }
    return letter / divider ;
}
float compute_score1(string text)
{


    return letter / divider ;
}

Upvotes: -1

Views: 83

Answers (1)

Lundin
Lundin

Reputation: 214810

In printf you need to type .2. Digits immediately after the % is the "field width" (padding with spaces etc if fewer digits than the number are there). The digits after the . is the precision so that's where you want the 2 to be. If you don't specify a digit after the . it gets taken as zero, so no decimals, which explains your result.

printf("%.2f", score);

Upvotes: 3

Related Questions