简体   繁体   English

“ rand()”不起作用,每次执行后我都会得到相同的数字

[英]“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. 所以我要为我的编程课创建一个ATM程序,长话短说,我必须创建大约四个随机数。 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)); 我有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. 在我的主要函数中,由于我的变量是全局变量,因此我试图将其移出全局变量旁边的main变量,这给我带来了无法解决的错误。 HELPPP!!!! 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;

srand is a function call, this can't be placed in file scope, you can only place declarations, there. srand是一个函数调用,不能放置在文件范围内,只能在此处放置声明。

Leave it in main , this is the place where it ought to be. 将其保留在main ,这是应该放置的地方。

the problem here is that you are trying to initialize your vars at file scope with function calls. 这里的问题是您试图通过函数调用在文件范围内初始化var。

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! 最好!

Call 呼叫

srand(time(NULL));

once at the start of main . main开始时一次。 To initialize global variables with some random value using rand , use: 要使用rand使用一些随机值初始化全局变量,请使用:

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

int account_number, pin, chk_acc_bal, sav_acc_bal;

int main()
{
  srand(time(NULL)); //Call srand in the start of main

  account_number = rand() % 5; //Initialize variables with a random value from here
  pin = rand() % 3; 
  chk_acc_bal = rand() % 4; 
  sav_acc_bal = rand() % 5;

  //Rest of the code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM