Search code examples
crandomsrand

"rand()" not working, i keep getting the same number after every execute


So i am creating a ATM program for my programming class, long story short, i have to create about four random numbers. My issue is my program will not create different numbers, the numbers i get when i execute my program are the same over and over. I had srand(time(NULL)); in my main function and since my variables were global i tried to move it out of main next to my global variables, this left me with a un-compliable error. HELPPP!!!!

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


int account_number = rand() % 5, pin = rand() % 3, chk_acc_bal = rand() % 4, sav_acc_bal = rand() % 5;

Solution

  • the problem here is that you are trying to initialize your vars at file scope with function calls.

    Just try initializing your variables within your main function. Something like (I tested and works):

    #include<stdio.h>
    #include<time.h>
    #include<stdlib.h>
    #include<string.h>
    
    int account_number, pin, chk_acc_bal, sav_acc_bal;
    
    int main(void)
    {
        srand(time(NULL));
    
        account_number = rand() % 5;
        pin = rand() % 3;
        chk_acc_bal = rand() % 4;
        sav_acc_bal = rand() % 5;
    
        printf("%d\n",account_number);
        printf("%d\n",pin);
        printf("%d\n",chk_acc_bal);
        printf("%d\n",sav_acc_bal);
    
        return 0;
    }
    

    Hope it helps. Best!