0

I have made a code to generate random no in set of two like coordinates like (1.00,4.00), (3.00,6.00) but i want the result in decimal like (1.45,4.87),(3.56,6.45) some digits after decimal my code show only zeros after decimal.

my code is

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

int main () {
    srand(time(NULL));
    int a[100][2],i,j;
    for (i=0; i<100; i++) {
        for (j=0; j<2; j++) {
            a[i][j]= rand()%11;
        }
    }
    for (i=0; i<100; i++) {
        printf("(");
        for (j=0; j<2; j++) {
            printf("%d",a[i][j]);
            if(j==0)
                printf(",");
        }
        printf(") ");
    }
    scanf("%d");
    return 0;
}
sampathsris
  • 21,564
  • 12
  • 71
  • 98
Nitin
  • 13
  • 1
  • 2
  • 5

1 Answers1

3

Use double instead of int

// int a[100][2],i,j;
double a[100][2];
int i, j;

Also write a function to generate floating point random numbers, rather than integer random numbers

// generate numbers in the interval [0, 1[
double randd_opened(void) {
    return rand() / (RAND_MAX + 1.0);
}

// generate numbers in the interval [0, 1]
double randd_closed(void) {
    return rand() / (double)RAND_MAX;
}

Note: multiplying a random number in the interval [0, 1] by x gives a random number in the interval [0, x].

pmg
  • 106,608
  • 13
  • 126
  • 198
  • What's the difference between those two functions in your answer? – Spikatrix May 31 '15 at 09:08
  • 1
    One gives random numbers in the interval `[0, 1[`, the other in the interval `[0, 1]` ... or `1` is a possible random value in one, but not the other. – pmg May 31 '15 at 09:12
  • 1
    Note: the task of *printing* a limited amount of decimals is best left to `printf`, and should not be attempted by something as inaccurate (and plain wrong) as trying to put "only" 2 or 3 decimals into the `double` (which is impossible). – Jongware May 31 '15 at 10:21
  • i am still not getting the desired result and the code you have give is in c++ i think. If you run my code it will result in 100 sets of numbers (2,4), (6,7) but i want in floating point (2.56,4.56) – Nitin May 31 '15 at 18:35
  • THANKS A LOT FOR HELP http://stackoverflow.com/questions/13408990/how-to-generate-random-float-number-in-c THIS WORKS FOR ME – Nitin Jun 01 '15 at 03:04