Error random was not declared in this scope

Учу Си (наконец-то серьёзно!). Написал для себя некую программу движения точки к случайным координатам.
  • Печать

Страницы: [1]   Вниз

Тема: random() в Си. Где он?  (Прочитано 4523 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
Кровавый

Учу Си (наконец-то серьёзно!).
Написал для себя некую программу движения точки к случайным координатам.

Функция rand() даёт число в промежутке [0; N-1]. Завязана с random();
Запускаю программу 5 раз подряд и вижу идентичный рисунок. Где же тут случайное число, если они всё время повторяются? ???

Железо: AMD FX8350 4.2Ghz + 2x4Gb Kingston HeyperX + Asus M5A97 R2.0 + HDD WD WZ10EZEX 1TB 7200 rpm + SSD 128 GB + Win 10 x64.


Оффлайн
SergeyIT

Где же тут случайное число, если они всё время повторяются?

Для отладки как раз это и надо.

Извините, я все еще учусь


Оффлайн
Кровавый

randomize

gcc ругается, что функция не объявлена:

./hello.cpp:53:21: error: ‘randomize’ was not declared in this scope

В какой библиотеке она содержится, если не секрет?


Пользователь решил продолжить мысль 18 Декабря 2011, 00:19:08:


Для отладки как раз это и надо.

Извините, что Вы подразумеваете под местоимением «это»?

Железо: AMD FX8350 4.2Ghz + 2x4Gb Kingston HeyperX + Asus M5A97 R2.0 + HDD WD WZ10EZEX 1TB 7200 rpm + SSD 128 GB + Win 10 x64.


Оффлайн
egorchik007

srand (time(0)); //установка генератора
int a = rand ();


Оффлайн
Кровавый

srand (time(0)); //установка генератора
int a = rand ();

Спасибо. Теперь путь меняется.

На первом запуске словил вот такое:

egor@egorlaptop:~/C++$ ./a.out
XIO:  fatal IO error 11 (Resource temporarily unavailable) on X server «:0»
      after 118 requests (118 known processed) with 0 events remaining.

Как это избежать?

PS, srand (time(0)); было добавлено перед каждым вызовом rand() в main().


эм… Гугл говорит, ошибка OpenGL. Ну и чёрт с ней!

« Последнее редактирование: 18 Декабря 2011, 00:45:49 от Кровавый »

Железо: AMD FX8350 4.2Ghz + 2x4Gb Kingston HeyperX + Asus M5A97 R2.0 + HDD WD WZ10EZEX 1TB 7200 rpm + SSD 128 GB + Win 10 x64.


Оффлайн
SergeyIT

что Вы подразумеваете под местоимением «это»?

То что при каждом запуске последовательность повторяется. В противном случае отладка программы может быть затруднена. При появлении ошибки зависящей от случайного события искать ее будет очень сложно.

Извините, я все еще учусь


Оффлайн
Кровавый

То что при каждом запуске последовательность повторяется. В противном случае отладка программы может быть затруднена. При появлении ошибки зависящей от случайного события искать ее будет очень сложно.

Преимущества и недостатки осознал. Спасибо.


Пользователь решил продолжить мысль 18 Декабря 2011, 00:46:11:


Думаю, тему можно закрыть. Всем ещё раз спасибо!

« Последнее редактирование: 18 Декабря 2011, 00:46:11 от Кровавый »

Железо: AMD FX8350 4.2Ghz + 2x4Gb Kingston HeyperX + Asus M5A97 R2.0 + HDD WD WZ10EZEX 1TB 7200 rpm + SSD 128 GB + Win 10 x64.


  • Печать

Страницы: [1]   Вверх

Status
Not open for further replies.

  • #1

when i write this statement in code blocks
randomize();
and
r1=random(991)+10;
the error is coming random not declared in the scope
and
randomize not declared in the scope



Aug 7, 2007



602



1



19,960

123


  • #2

the function that you are looking for is rand() not random().

rand() will return a random integral number between 0 and RAND_MAX

If you wish to generate a random number less than RAND_MAX, take the modulus of the returned value and your own max value.

For example,

int my_random_value = 0;
int my_max_value = 500;
my_random_value = rand() % my_max_value

will generate a random number between 0 and 499. If you wish to normalize this to the range 1 to 500, simply add 1

my_random_value = (rand() % my_max_value) + 1



Aug 7, 2007



602



1



19,960

123


  • #2

the function that you are looking for is rand() not random().

rand() will return a random integral number between 0 and RAND_MAX

If you wish to generate a random number less than RAND_MAX, take the modulus of the returned value and your own max value.

For example,

int my_random_value = 0;
int my_max_value = 500;
my_random_value = rand() % my_max_value

will generate a random number between 0 and 499. If you wish to normalize this to the range 1 to 500, simply add 1

my_random_value = (rand() % my_max_value) + 1



Jan 13, 2011



4,165



4



35,260

1,357


  • #3

CodeBlocks can be used for variery of programming languages. Assuming that you’re using it for C/CPP, you might also want to make sure

appears in the first couple of your source file.
Help on rand and random can be obtained on the command line

Status
Not open for further replies.
Thread starter Similar threads Forum Replies Date

B

Question spawn a command block machine Apps General Discussion 2 Apr 13, 2020

R

how to block a file in windows10 pro Apps General Discussion 11 Mar 5, 2019

C

Solved! How to block Rap music on my youtube account Apps General Discussion 2 Jan 4, 2019

C

How do you get pass a blocked website on a school chromebook? Apps General Discussion 3 May 15, 2018

henrytcasey

How to Use Chrome’s New Autoplay Video Blocking Apps General Discussion 1 May 4, 2018

S

To block the ads or not to block that is the question Apps General Discussion 3 Apr 7, 2018

J

Laptop blocked by some friend Apps General Discussion 1 Apr 5, 2018

C

how do you block hapara? Apps General Discussion 1 Mar 19, 2018

Mighty

Solved! «This app is blocked for your protection» during boot. Which app??? Apps General Discussion 9 Jan 3, 2018

A

How to use Java in Code Blocks Apps General Discussion 8 Nov 16, 2017

A

Code Blocks compile Apps General Discussion 1 Aug 25, 2017

J

how can i veiw my messages in messenger if im on an administritve block from facebook Apps General Discussion 1 Jul 26, 2017

O

Bandicam Uninstall Blocked Apps General Discussion 1 Apr 8, 2017


G

New Lego-Compatible Blocks Teach Kids to Code Apps General Discussion 0 Mar 8, 2017

R

My gmail account doesn’t have the dropdown menu feature. How else can I block unwanted emails? Apps General Discussion 3 Nov 3, 2016

kol12

Review blocked sign-in attempt Google. Apps General Discussion 7 Sep 15, 2016

J

IE 11, how do I block an entire domain. Apps General Discussion 6 Aug 2, 2016

Durwesh Naeem

Asus suite Audio plug ins blocking bittorent Apps General Discussion 2 Jul 24, 2016

P

Is Explorer blocking Chrome? Apps General Discussion 2 Jul 19, 2016

R

how to stop and block the tenminutestokill website to pop up ? Apps General Discussion 1 Feb 17, 2016

  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions
  • Topics

Доброго времени суток. Есть код написанный на Си, но при компиляции в DevC++ выдает ошибку
[Error] ‘randomize’ was not declared in this scope
[Error] ‘random’ was not declared in this scope
Подскажите как можно исправить

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
 
long iC, iM;
void printmas(int *m, int n)
{for (int i=0; i<n; i++)
{printf("%4i",m[i]);}
printf("n");}

void initdown(int *m, int n)
{
  for (int i=0; i<n ; i++) {
    m[i] = n-i-1;
  }
}

void initup(int *m, int n)
{
  for (int i=0; i<n ; i++) {
    m[i] = i;
  }
}

void initrandom(int *m, int n)
 
{randomize();
  for (int i=0; i<n ; i++) {
    m[i] = random(500);
  }
}

long consum(int *m, int n)
{
  long sum=0;
 
  for (int i=0; i<n ; i++)
    sum += m[i];
 
  return sum;
}

int kolser(int *m, int n)
{
  int kser=1;
 
  for (int i=1; i<n; i++)
    if (m[i] < m[i-1]) kser++;
 
  return kser;
}

void sortpr(int *m, int n)
{
  iM=0; iC=0; 
 
  for (int i=0; i<n-1; i++) {
    int min = i;
 
    for (int j=i+1; j<n; j++) {
      if (m[j] < m[min]) min = j;  

      iC++;
    }
 
    int tmp;
    tmp = m[i]; m[i] = m[min]; m[min] = tmp;
    iM += 3;
  }
}

void sortpuz(int *m, int n)
{
  iM=0; iC=0; 
 
  for (int i=1; i<n; i++)
    for (int j=n-1; j>=i; j--) {
      iC++;
      if (m[j-1] > m[j]) { 
                           
        int tmp;
        tmp = m[j-1]; m[j-1] = m[j]; m[j] = tmp;
        iM += 3;
      }
    }
}
 
void sortsh(int *m, int n)
{
  iM=0; iC=0; 
  int i;
 
  int l=0;
  int r=n-1, k=n-1;
 
  while (l < r) { 
    for (i=r; i > l; i--) {
      iC++;
      if (m[i-1] > m[i]) { 
                           
        int tmp;
        tmp = m[i-1]; m[i-1] = m[i]; m[i] = tmp;
        iM += 3; k = i;
      }
    }
 
    l = k;
 
    for (i=l; i < r; i++) { 
      iC++;
      if (m[i] > m[i+1]) { 
                           
        int tmp;
        tmp = m[i+1]; m[i+1] = m[i]; m[i] = tmp;
        iM += 3; k = i;
      }
    }
    r = k;
  }
}
 
int main(void)
{
  int *o, *m;
  int n, metod;
 
  fflush(stdin);
  printf("‡*¤*©ГўВҐ Г**§¬ВҐГ* ¬*ГЎГЎВЁВў*. N=");
  scanf("%i",&n);
  printf("n");
  o = (int *)malloc(n*sizeof(int));
  m = (int *)malloc(n*sizeof(int));
 
  do {
    printf("‡*¤*©ГўВҐ ГЎВЇ®ГЎ®ВЎ ВЁ*¨æ¨*«ВЁ§*樨 ¬*ГЎГЎВЁВў*.n");
    printf("1 - ã¡ë¢*î騩.n");
    printf("2 - ГЎ«ГЈГ§*©*Г«©.n");
    printf("3 - Вў®§Г**ГЎГў*î騩.n");
    printf("0 - ‚ë室 ВЁ§ ВЇГ*®ВЈГ**¬¬Г«.n");
    scanf("%i",&metod);
  } while ( metod <0 || metod >3);
  printf("n");
 
  switch ( metod ) {
    case 0: 
      exit(0);
      break;
    case 1: 
      initdown(o, n);
      break;
    case 2: 
      initrandom(o, n);
      break;
    case 3: 
      initup(o, n);
      break;
  }
  printf("Л†ГЎГҐ®¤*Г«© ¬*ГЎГЎВЁВўn");
  printmas(o,n);
  printf("Е*®*ГўГ*®«Г¬**ГЇ ГЎГЈ¬¬* ¤® ГЎ®Г*ГўВЁГ*®ВўВЄВЁ = %lin",consum(o,n));
  printf("Е*®«ВЁГ§ВҐГЎГўВў® ГЎВҐГ*ВЁ© ¤® ГЎ®Г*ГўВЁГ*®ВўВЄВЁ = %in",kolser(o,n));
  printf("n");
 
  while (1) {
    do {
      printf("‡*¤*©ГўВҐ ГЎВЇ®ГЎ®ВЎ ГЎ®Г*ГўВЁГ*®ВўВЄВЁ.n");
      printf("1 - ¬ВҐГў®¤ ВЇГ*ГЇ¬®ВЈ® ¢ë¡®Г**.n");
      printf("2 - ¬ВҐГў®¤ ВЇГЈ§Г«Г*ìª*.n");
      printf("3 - ¬ВҐГў®¤ ЛњВҐ©ВЄВҐГ**.n");
      printf("0 - ‚ë室 ВЁ§ ВЇГ*®ВЈГ**¬¬Г«.n");
      scanf("%i",&metod);
    } while ( metod <0 || metod >3);
    printf("n");
 
    memcpy(m,o,n*sizeof(int));
 
    switch ( metod ) {
      case 0: 
        exit(0);
        break;
    case 1: 
        sortpr(m, n);
        break;
      case 2:
        sortpuz(m, n);
        break;
      case 3: 
        sortsh(m, n);
        break;
    }
 
    printf("ЕЅГўГЎ®Г*ГўВЁГ*®Вў***Г«© ¬*ГЎГЎВЁВўn");
    printmas(m,n);
    printf("Е*®*ГўГ*®«Г¬**ГЇ ГЎГЈ¬¬* ВЇ®ГЎ«ВҐ ГЎ®Г*ГўВЁГ*®ВўВЄВЁ = %lin",consum(m,n));
    printf("Е*®«ВЁГ§ВҐГЎГўВў® ГЎВҐГ*ВЁ© ВЇ®ГЎ«ВҐ ГЎ®Г*ГўВЁГ*®ВўВЄВЁ = %in",kolser(m,n));
    printf("Е*®«ВЁГ§ВҐГЎГўВў® ГЎГ**Вў*ВҐ*ВЁ© = %li ВЁ ВЄ®«ВЁГ§ВҐГЎГўВў® ВЇВҐГ*ВҐГЎГ««®ВЄ = %lin",iC,iM);
    printf("n");
  }
 
  return 0;
}
  • Forum
  • General C++ Programming
  • <random> not working?

<random> not working?

I’ve been trying to use the <random> header, as shown in the reference page here:
http://www.cplusplus.com/reference/random/

This is the code in question:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void DisplaySix(unsigned char iNumber)
{
  unsigned int iDisplay;
  default_random_engine engine;
  uniform_int_distribution<int>distribution(1,6);
  do
  {
    iDisplay=distribution(engine);
    cout << iDisplay;
    cout << "n";
    iNumber--;
  }
  while(iNumber>0);
  return;
}

I assume that the code above would produce and display a «random» number between 1 and 6 equal to X times, where X is the variable «iNumber» passed to the function.

I am using Code::Blocks (not sure if that matters).
When compiling I get these errors for each occurrence of the code above:


In function 'void DisplaySix(unsigned char)':
error: 'default_random_engine' was not declared in this scope
error: expected ';' before 'engine'
error: 'uniform_int_distribution' was not declared in this scope
error: expected primary-expression before 'int'
error: expected ';' before 'int'
error: 'engine' was not declared in this scope
error: 'distribution' was not declared in this scope

I tried removing the «using namespace std» line (thinking that in some way, it might help), and manually adding «std::» to each object in the std namespace, along with the «default_random_engine» and «uniform_int_distribution» objects as shown in the <random> reference page, which resulted in these errors as well:


error: 'default_random_engine' is not a member of 'std'
error: 'uniform_int_distribution' is not a member of 'std'

I’m wondering…is it something I’ve done wrong? How do you get these to work, or would it be better to just use rand() and modulus?
Note: I am trying to avoid using rand() and modulus due to the higher probability of lower results for more of a seemingly «random» number each time.

Thank you for any help and/or insight into what might be going wrong here.

Also, In the code example above, I have shown the «DisplaySix()» function of my program. However, in the entire source code, there are multiple functions, all using different max values. However, all of these functions have the same errors when compiling. So, if there is an easier/better way to get «random» numbers between 1 and X, please let me know.

I am using Code::Blocks (not sure if that matters).

It does matter. The code snippet works, here for example: http://ideone.com/VYuULv but only if the compiler supports C++11. If you don’t have such compiler, you can use TR1 or boost.random, but most likely all you need to do is add -std=c++11 or -std=c++0x to your project options.

Last edited on

I apologize, I should have mentioned that in my original post.

It did tell me something about that file being experimental and needing to enable one of those options. So, I went to Settings -> Compiler and debugger… -> Compiler settings -> Compiler flags, and enabled the «Have g++ follow the coming C++0x ISO C++ language standard [-std=c++0x]» option.

I had that enabled when I tried to compile and got those errors. I checked again, and do not see an option for «-std=c++11».

Edit* I checked the link that you posted, and it does seem to work. So, maybe, the problem is in another part of the source code? I rewrote the program using rand() so that it would compile. I’m still interested in knowing what I did wrong though, so I’ll write it back to the way it originally was, and post the entire code here.

Last edited on

Topic archived. No new replies allowed.

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • [SOLVED] Codeblocks,C++, rand() was not declared.

  1. Question Codeblocks,C++, rand() was not declared.

    Hopefully i posted this in the right area (sorry if i didnt).
    Hey there. Learning C++ from C++ For Dummies All-In-One Second edition where they teach it with Codeblocks (the reason why i bought it).

    Ok, my problem is basically I get an error as such when building:

    Code:

    error; 'rand' was not declared in this scope

    Here’s my sourcode (slightly modified from the books version. Just added a prototype for the function).
    rand() is located in the GetSecretCode() function

    Code:

    #include <iostream>
    #include <sstream>
    
    using namespace std;
    
    string *GetSecretCode();
    
    int main()
    {
        string *newcode;
        int index;
    
        for ( index = 0; index < 10; index++ )
        {
            newcode = GetSecretCode();
            cout << newcode << endl;
        }
    
        cout << "All done here" << endl;
    
        return 0;
    }
    
    string *GetSecretCode()
    {
        string *code = new string;
        code->append("CR");
    
        int randomnumber = rand();
        ostringstream converter;
        converter << randomnumber;
    
        code->append(converter.str());
        code->append("NQ");
    
        return code;
    }

    What am I missing code wise?
    something I didn’t «#include» ?


  2. Re: Codeblocks,C++, rand() was not declared.

    rand is defined in cstdlib (there is no standard c++ random function yet). so include:
    #include <cstdlib>

    also you have memory leaks in your code as you don’t delete the created string
    generally you should avoid dynamically allocating stuff where it is not needed.
    you can rewrite it to something like this:

    Code:

    // very long string which might be expensive to copy, so use a reference
    void createCopyExpensiveString(string & str) {
    // dostuff
    }
    
    // short string, cheap to copy
    string createShortString()
    {
       return "shortstring";
    }
    
    void main()
    {
      string str;
      createCopyExpensiveString(str);
      cout << str << endl;
      string str2 = createShortString();
      cout << str2 << endl;
    } // str and str2 go out of scope here and get deleted automatically

    Last edited by MadCow108; October 6th, 2009 at 03:35 PM.


  3. Smile Re: Codeblocks,C++, rand() was not declared.

    Hey thanks, it worked off the bat.

    Just out of curiosity I tried it on Vista as well but without cstdlib
    and it works…..whats with that?

    It’s obvious now that although they promote crossplatform code in this For Dummies book, they only tested the code on Winduhs…

    For shame..
    Any idea why it works differently?


  4. Re: Codeblocks,C++, rand() was not declared.

    It is a usual phenomenon…

    Many compilers include some «hidden» libraries that support the underlying operating system. For example, in Vista, your compiler may add <cstdlib> subtlely.

    Another example is GCC’s linker in Linux that automatically adds «stdlib.h» by default, without prior declaration by the programmer.

    I hope I made it clear for you.

    Happy coding!


  5. Talking Re: Codeblocks,C++, rand() was not declared.

    Thanks guys.
    that was the case with C when I learned it earlier this year..
    MadCow, I shall ponder upon your unique(odd?) code and when I have better grasped C++ then maybe I shall better understand it.
    Toodles~


  6. Re: Codeblocks,C++, rand() was not declared.

    Quote Originally Posted by myromance123
    View Post

    Thanks guys.
    that was the case with C when I learned it earlier this year..
    MadCow, I shall ponder upon your unique(odd?) code and when I have better grasped C++ then maybe I shall better understand it.
    Toodles~

    MadCow’s code isn’t really odd. He makes a great point. A lot of people use a lot of pointers when they’re not really needed. It is important to really understand what pointers are for, and only use them when necessary because pointers can be the main source for memory leaks. If you don’t really need them, don’t use them.

    Today you are You, that is truer than true. There is no one alive who is Youer than You. — Dr. Seuss


  7. Re: Codeblocks,C++, rand() was not declared.

    ok i new to programming and went i try to use the �rand� i get this was not declared in this scope|

    #include <iostream>
    #include <cmath>

    int main()
    {
    using namespace std;

    double num1;
    num1 = rand ();
    cout << num1 <<endl;

    return 0;
    }


  8. Re: Codeblocks,C++, rand() was not declared.

    Quote Originally Posted by foxgoooo
    View Post

    ok i new to programming and went i try to use the ‘rand’ i get this was not declared in this scope

    Probably because rand belongs to cstdlib, not cmath. Also, avoid resurrecting long forgotten threads.


Tags for this Thread

Bookmarks

Bookmarks


Posting Permissions

Понравилась статья? Поделить с друзьями:
  • Error radeon kernel modesetting for r600 debian
  • Error r009 limit of 60 segments for a single road exceed
  • Error r s a c s c cryptoprivatkeyvalidator error on test signature
  • Error querying ocsp responder
  • Error querying database