Thread: Problem with decimals

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    92

    Problem with decimals

    Hello I wrote this program to generate 10 random numbers and put it in a array with 10 elements. But I want the results to be put into i decimal places. like 1.3 or 0.7 ect.... But instead it's like 1.0 and 0.0 can some one please fix my code for me or help me in any other way.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define size 10
    int main()
    {
       int i;
       float x[size];
       
        /* Randomise the random number generator */
        srand((unsigned)time(NULL));
        /* Assign random values to the variable */
        for (i=0; i<10; i++)
            x[i] = (rand()%26)/14;
        /* Display the contents of the array */
        for (i=0; i<10; i++)
            printf("element %d has the value %1.1f\n", i, x[i]);
        return 0;
        }

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    The trouble you have is that
    (rand()%26)/14 divides one int by another int and the result is still an int.
    change the line to
    Code:
    x[i] =(rand()%26)/14.0f;
    Kurt

  3. #3
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Quote Originally Posted by ZuK
    The trouble you have is that
    (rand()%26)/14 divides one int by another int and the result is still an int.
    change the line to
    Code:
    x[i] =(rand()%26)/14.0f;
    Kurt
    Be aware that because of the %26, you will only get 26 different values, from 0.0 to 25/14.0. Is that what you want to achieve?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  2. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  3. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  4. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  5. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM