Checking the digit after comma C

Viewed 374

I am a bit stuck on a code i am writing right now. I need to check a double number, if the digit after the comma is two. My code always tells me, that there a too much.

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 
//Code by Ninto


int main(){
    double numbers[25] = {0.0};
    int twoOnDecile = 0;
    srand(time(NULL));

    for(int i = 0;i <= 24;i++){
        numbers[i] = (double)rand()/RAND_MAX*64-32;
        if(i % 8 == 0)printf("\n");
        else printf(";");
        printf("%7.2lf",numbers[i]);
        if((numbers[i]-(int)numbers[i])/2.0 >= 0.1&&(numbers[i]-(int)numbers[i])/2.0 < 0.4)twoOnDecile++;
        if((numbers[i]-(int)numbers[i])*-1/2.0 >= 0.1&&(numbers[i]-(int)numbers[i])*-1/2.0 < 0.4)twoOnDecile++;
    }
    printf("\n2 on decile rank:%d",twoOnDecile);
    return 0;
}
2 Answers

There is a math.h library function called modf that can extract the fractional part from a number and will make your job much easier:

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <math.h>

int main()
{
    double numbers[25] = {0.0};
    int twoOnDecile = 0;
    srand(time(NULL));
    double fractional;
    double integer;

    for (int i = 0; i <= 24; i++)
    {
        numbers[i] = (double)rand() / RAND_MAX * 64 - 32;
        if (i % 8 == 0)
            printf("\n");
        else
            printf(";");
        printf("%7.2lf", numbers[i]);

        fractional = modf(numbers[i], &integer);
        
        // you could also use fabs() instead of negative value condition
        if ((fractional >= 0.2 && fractional < 0.3) || (fractional > -0.3 && fractional <= -0.2))
        {
            twoOnDecile++;
        }
    }
    printf("\n2 on decile rank:%d", twoOnDecile);
    return 0;
}

Live demo

I suggest you some other ways to achieve your goal:

You can write your double into a string and check with a for loop the character after the comma:

#include<string.h>

...

/* The Number */
double x = ...
/* String representation of the number */
char my_doub[15];
sprintf(my_doub, "%lf", x);

/* First occurence of '.' */
char *comma = strchr(my_doub, '.');
/* Control next character */
if(*(comma+1) == '2'){
    ...
}

If you're forced to work with numbers you could do this way:

if X = xyz.abc

  • multiply X by 10 --> 10 * X is xyza.bc
  • Type cast it to int --> (int) X is xyza

Now X % 10 will be a , and you can test it with 2

if((int)(X*10) % 10 == 2){
...
}

Note: this second method would have problems with large doubles: 10*x may be too large

Related