Error srand was not declared in this scope

Dev-C++ version 5.5.2 (Windows 7) gives compilation error that occurs in the last line in main():

[Error] ‘srand48’ was not declared in this scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <sys/time.h>
#include <cmath>
#include <cstdlib>
#include <stdlib.h>

extern double drand48();
extern long lrand48(/*long*/);
extern int rand();
extern void srand(long seedval);



//main program
main()
{

//set random number generator
struct timeval tp;
struct timezone tzp;
gettimeofday(&tp,&tzp);
srand48(tp.tv_usec); //compilation error occurs here: [Error] 'srand48' was 
                     //not declared in this scope
}

Last edited on

> extern void srand(long seedval);
There is no 48 here.

But your modification gives error: s.cpp:(.text+0x23): undefined reference to `srand(long)’

I’d suggest you delete these lines.

1
2
3
4
extern double drand48();
extern long lrand48(/*long*/);
extern int rand();
extern void srand(long seedval);

There’s a whole load of rand related prototypes already in stdlib.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
       #include <stdlib.h>

       double drand48(void);

       double erand48(unsigned short xsubi[3]);

       long int lrand48(void);

       long int nrand48(unsigned short xsubi[3]);

       long int mrand48(void);

       long int jrand48(unsigned short xsubi[3]);

       void srand48(long int seedval);

       unsigned short *seed48(unsigned short seed16v[3]);

       void lcong48(unsigned short param[7]);

       int rand(void);

       int rand_r(unsigned int *seedp);

       void srand(unsigned int seed);

Thanks for the suggestion. but the original issue still remains.

Are these your own functions or existing functions that you just are just trying to use?

I have copied program on Simulated Annealing from a book Alan Parker, Algorithms and Data Structures in C++, in last section of chapter 3.

Well, srand48 is not a standard C++ function. It seems to be some kind of POSIX function. Not sure it’s available on Windows.

Yeah, they’re common extensions, if your ‘common’ isn’t windows (I guess).

The very next lines in the manual page.

1
2
3
4
5
6
   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       All functions shown above: _SVID_SOURCE || _XOPEN_SOURCE
///
CONFORMING TO
       POSIX.1-2001, POSIX.1-2008, SVr4.

I suppose you could fake things with

1
2
3
4
5
6
7
8
9
long lrand48() {
    return rand();
}
double drand48() {
    return rand() / (double)RAND_MAX;
}
void srand48(long seedval) {
    rand(seedval);
}

The ’48’ versions would typically have much longer cycle times than the standard rand functions.

But if you really want to improve things, then use this instead.
http://www.cplusplus.com/reference/random/

Thanks, a lot for your detailed response. I would try your trick soon. However, I ran on Cygwin & got it running using g++. So, it is possibly a Unix vs Windows environment issue.

However, the code was problem area reported in a bigger code on Simulated Annealing, which is from book by Alan Parker, Algorithms and Data Structures in C++, in last section of chapter 3.

I am still facing the Segmentation fault on running g++ there, with the command: $ g++ -Wall -Wextra -Werror -c sp3.cpp -o sp3.o; followed by ./sp2.

The full code is at: https://onlinegdb.com/HyruMTmdN. It reported the same error at onlinegdb too, but in absence of any details provided, cannot understand what is causing the error.

If the link is not accessible, please tell; then will try some other option — although I feel attaching file is not an option here. Tried putting the code here, but was rejected due to length more than the max. allowable.

Last edited on

Yes, something funny with one of the loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
$ g++ -Wall -Wextra -g bar.cpp
bar.cpp: In function ‘void create_operation_array()’:
bar.cpp:86:49: warning: operation on ‘i’ may be undefined [-Wsequence-point]
     for(j=0;j<NO_SQUARES;i++) op[i++] = PLUS+i%2;
                                                 ^
bar.cpp: At global scope:
bar.cpp:319:6: warning: ISO C++ forbids declaration of ‘main’ with no type [-Wreturn-type]
 main()
      ^
bar.cpp: In function ‘int main()’:
bar.cpp:323:23: warning: unused variable ‘random_neighbor_cost’ [-Wunused-variable]
     int optimal_cost, random_neighbor_cost;
                       ^

Well, two funnies actually.
1. The for loop starts off with j, but ends up incrementing i.
Such a loop will never exit.

2. You should really write the statement as

1
2
3
4
 {
    op[i] = PLUS+i%2;
    i++;
}

And also make main return an int explicitly.

Thanks a lot for telling the errors in logic. But, the program is taking infinite time to run, both in onlinegdb, & in cygwin. The book even states that the program may not be able to find soln. The new code with only the warnings removed is at: https://onlinegdb.com/SJ0dzGSd4. Would soon implement your suggestions.

It ended after around 30 mins. in cygwin, & am giving the last line of outputs:
Calculated cost 1
data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<data[present_op[i]]<<++**++*+++

It seems all is wrong, but would see why cost is 1 only.

Last edited on

I’m not surprised it takes so long with all that debug code you’ve thrown in.

And you didn’t fix ALL the problems I pointed out, so what next?

default: cout<<data[present_op[i]]; break;

I changed this to output the value, rather than just printing a silly string.


$ time ./a.out | tail -3
in print_result 
Calculated cost 1
11111111111++**++*+*+

real	0m0.568s
user	0m0.664s
sys	0m0.152s
$ time ./a.out | tail -3
in print_result 
Calculated cost 1
11111111111*++*+*+**+

real	0m0.493s
user	0m0.576s
sys	0m0.140s
$ time ./a.out | tail -3
in print_result 
Calculated cost 1
11111111111*++*++++*+

real	0m0.550s
user	0m0.604s
sys	0m0.184s

Thanks, but as never ran a such long running program; so the overhead incurred by printf() was not known. Now, it runs un-believably faster in comparison.

In fact, am unable to understand the workings of the program properly. But that is another issue.

Would request you to quantitatively compare by some way the overhead incurred by printf() (in this program, as earlier) without making a call to them, as it takes a lot of time then.

Last edited on

Sorry, for the last query as could not understand the significance of ‘time’ used for timing. I timed the commented version (named sp_c.cpp) by the set of commands: $ g++ sp_c.cpp -o sp_c, time ./sp_c | tail -3. And it took ten times (i.e., 3-4 sec.) the time as compared to the time reported by you for the un-commented version.

But, there is still something to ask for.
If try the commented version (named sp_c.cpp) as at : https://onlinegdb.com/Bkeuc5H_V, by the set of commands (on cygwin) : $ g++ sp_c.cpp -o sp_c, ./sp_c; then it took around 30 mins. to complete.
While the un-commented version (named sp_nc.cpp) still completed in under a second by the commands: $ g++ sp_nc.cpp -o sp_nc, ./sp_nc.

I am curious if the delay in the commented version is a function of printf (that caused to have only a 10 times difference), or a function of display. By display, I mean the screen display of the printf took so much addtl. time. If so, then the display is another factor, & hence causes a very high order of difference in time taken, i.e. around 20 mins. vs 3-4 seconds, as for program timed for printf.

Last edited on

I am unable to find the significance of (lrand48() >> 4) in the statement at line #54 : build_list->side = (lrand48() >> 4)%(SQUARE_SIZE_LIMIT)+1; for the code in function: void get_list_start(square_list ** list), in file at https://onlinegdb.com/S1DQiAH_E

Any pointer in that direction would help me a lot.

Last edited on

> By display, I mean the screen display of the printf took so much addtl. time.
Exactly.
For every line output, it has to scroll the 50-100 lines visible on screen, and maybe 1000’s of lines in the history buffer (what scrollback buffer did you set).

1
2
$ ./a.out | wc -l
18053368

Considering that your instrumented code outputs over 18 MILLION lines of text, that’s a hell of a lot of scrolling!.
You might want to consider targeting your logging at specific areas of interest. You’re not going to wade through that volume of output and discover meaning.

Using «

| tail -3

» is very efficient, since tail only keeps an internal ring buffer of the 10 most recent lines. It only outputs when it’s input is complete (the pipe is closed).

> as compared to the time reported by you for the un-commented version.
Not all machines are equal.
Cygwin is a compatibility layer between the OS your program expects (Linux) and the OS you really have (Windows). What needs to be done to maintain that illusion varies depending on what you’re doing, but the cost is never zero.

Besides, my machine will take seconds to run the program if I try to do any work with the 200MB of data the program spews out.

It’s only meaningful to get performance data on the version without voluminous printfs, when optimisation is enabled.

1
2
$ g++ -O2 sp_nc.cpp -o sp_nc
$ ./sp_nc

> I am unable to find the significance of (lrand48() >> 4) in the statement at line #54
https://en.wikipedia.org/wiki/Linear_congruential_generator
Such generators are notoriously bad random number generators in the least significant bits. Some examples of rand()%2 will produce nothing but 0,1,0,1,0,1,0,1,0,1,0 ….

So >>4 will throw away the bottom 4 bits, presumably with the hope that the resulting pseudo random number is a bit more random and a bit less pseudo.

Very sorry, but had bad experience in getting no response earlier. So, placed elsewhere in parallel, the initial problem.
I got some good response, that continued me there.

Also, I am first time here; so deserve excuse for this error; as knew nothing about the responsiveness here.

Last edited on

HHHggggHHH

3 / 3 / 0

Регистрация: 27.04.2019

Сообщений: 59

1

27.04.2019, 10:30. Показов 3999. Ответов 4

Метки с++ массивы (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <TCHAR.h>
#include <iostream>
#include <time.h>
#include <ctime>
using namespace std;
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
 
    int size = rand() % 150;
    size += 50;
 
    int *mas = new int [size];
 
    int *p = NULL;
    int *t = NULL;
 
    int r;
    int temp;
    int pos;
 
 
    p = mas;
    for (int i = 0; i < size; i++, p++)
    {
        r = rand() % 200;
        r -= 100;
        *p = r;
    }
 
    cout << "razmer masiva: " << size << 'n';
    cout << "massiv do preobrozovaniya:" << 'n';
    p = mas;
    for (int i = 0; i < size; i++, p++)
        cout << *p << ' ';
 
  
    for (int i = 0; i < size; i++)
    {
        p = mas;
        t = (mas + 1);
        for (int j = 0; j < size - 1; j++, p++, t++)
            if (*p > *t)
            {
                temp = *p;
                *p = *t;
                *t = temp;
            }
    }
 
    p = mas;
    pos = size;
    
    for (int i = 0; i < size; i++, p++)
        if (*p > 0)
        {
            pos = i;
            break;
        }
    
    for (int i = 0; i < pos; i++)
    {
        p = mas;
        t = (mas + 1);
        for (int j = 0; j < pos - 1; j++, p++, t++)
            if (*p == 0)
            {
                temp = *p;
                *p = *t;
                *t = temp;
            }
    }
 
    cout << "nn" << "massive posle preobrozovaniya:" << 'n';
    p = mas;
    for (int i = 0; i < size; i++, p++)
        cout << *p << ' ';
 
    getchar();
 
    delete [] mas;
 
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

27.04.2019, 10:30

4

Verevkin

Нарушитель

8388 / 4391 / 1009

Регистрация: 12.03.2015

Сообщений: 20,566

27.04.2019, 10:56

2

Ну зачем же так?

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <time.h>
#include <ctime>
using namespace std;
 
 
int main(int argc, char* argv[])
{
    srand(time(NULL));
 
    int size = rand() % 150;
    size += 50;
 
    int *mas = new int [size];
 
    int *p = NULL;
    int *t = NULL;
 
    int r;
    int temp;
    int pos;
 
 
    p = mas;
    for (int i = 0; i < size; i++, p++)
    {
        r = rand() % 200;
        r -= 100;
        *p = r;
    }
 
    cout << "razmer masiva: " << size << 'n';
    cout << "massiv do preobrozovaniya:" << 'n';
    p = mas;
    for (int i = 0; i < size; i++, p++)
        cout << *p << ' ';
 
 
    for (int i = 0; i < size; i++)
    {
        p = mas;
        t = (mas + 1);
        for (int j = 0; j < size - 1; j++, p++, t++)
            if (*p > *t)
            {
                temp = *p;
                *p = *t;
                *t = temp;
            }
    }
 
    p = mas;
    pos = size;
 
    for (int i = 0; i < size; i++, p++)
        if (*p > 0)
        {
            pos = i;
            break;
        }
 
    for (int i = 0; i < pos; i++)
    {
        p = mas;
        t = (mas + 1);
        for (int j = 0; j < pos - 1; j++, p++, t++)
            if (*p == 0)
            {
                temp = *p;
                *p = *t;
                *t = temp;
            }
    }
 
    cout << "nn" << "massive posle preobrozovaniya:" << 'n';
    p = mas;
    for (int i = 0; i < size; i++, p++)
        cout << *p << ' ';
 
    getchar();
 
    delete [] mas;
 
    return 0;
}



0



3 / 3 / 0

Регистрация: 27.04.2019

Сообщений: 59

27.04.2019, 11:07

 [ТС]

3

ВСЕ РАВНО НЕ РАБОТАЕТ !!! 1) C:UsersàäìèíDesktopëàá 2main.cpp [Error] ‘srand’ was not declared in this scope 2)C:UsersàäìèíDesktopëàá 2main.cpp [Error] ‘rand’ was not declared in this scope



0



ProgItEasy

454 / 278 / 163

Регистрация: 17.04.2019

Сообщений: 1,603

27.04.2019, 11:08

4

HHHggggHHH,

C++
1
#include <cstdlib>



0



3 / 3 / 0

Регистрация: 27.04.2019

Сообщений: 59

27.04.2019, 11:14

 [ТС]

5

Спасибо заработало !!!!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

27.04.2019, 11:14

Помогаю со студенческими работами здесь

Что это значит srand(time(NULL))?
srand(time(NULL));

Std::sort, lambda-выражения, time(NULL) и srand()
#include &lt;algorithm&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;time.h&gt;

using namespace…

rand(time(NULL)
Необходимо получить диапозон случайных чисел от 1 до 6.

Я это пытаюсь делать вот таким образом…

Блин, для ЧЕГО НУЖНА Функция CREATE TABLE invoice( inv_id INT AUTO_INCREMENT NOT NULL , usr_id INT NOT NULL , prod_id INT NOT NULL , quantity INT NOT
Погуглив, так и не смог толком понять.
Есть тут ГУРУ по mysql Которые могут на пальцах или на…

Часто или иногда вызывается исключение по адресу 0x00007FF82427B760 (sfml-graphics-2.dll) | ошибка в srand(time(0)
С неопределённой вероятностью я получаю ошибку

в различных местах моего кода и кода самой…

rand, srand и т.д
Дана целочисленная матрица A (N,M), в которой имеются ровно два одинаковых элемента. Найти индексы…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

5

Не понимаю ошибок в основной программе на С ++

#include <iostream>

using namespace std;

int main(void) {
    int number, guess;

    srand(time(NULL));
    number = rand() % 101;

    cout << "Guess a number between 0-100: ";
    cin >> guess;

    if(number > guess) {
        cout << "The number is greater!n";
    }
    else if(number < guess) {
        cout << "The number is smaller!n";
    }
    else {
        cout << "Cognratulations! The number is "number"!n";
    }
    cin-get();

    return 0;
}
error: 'srand' was not declared in this scope
error: 'rand' was not declared in this scope
error :expected ';' before 'number'

Jonathan Dewein
07 янв. 2012, в 19:43

Поделиться

Источник

Вам нужно добавить:

#include <cstdlib>

включить srand() и rand()

Когда вам нужно использовать такие функции, просмотр этих страниц (или их поиск в Google) подскажет вам, какие заголовки вы должны включить.

http://www.cplusplus.com/reference/clibrary/cstdlib/

Brian Roach
07 янв. 2012, в 15:43

Поделиться

В дополнение к другому ответу

cout << "Cognratulations! The number is "number"!n";

Это не работает. Кажется, вы пытаетесь построить строку из «Cognratulations! Number», number и «!N», что возможно (но не с этим синтаксисом), но проще было бы сначала напечатать первую строку, затем число и, наконец, вторую строку.

cout << "Cognratulations! The number is " << number << "!n";

hvd
07 янв. 2012, в 16:29

Поделиться

Ещё вопросы

  • 0curl возвращает старую версию страницы
  • 0Угловая нг-сетка отключает автоматическую генерацию столбцов
  • 0Symfony2 как получить диспетчер сущностей в Listener
  • 1CKeditor не отображается на странице asp.net со скрытым div
  • 0Правильный способ в PHP для форматирования / экранирования строки для использования в XML
  • 0Форма PHP не отправляется на следующую страницу
  • 1OnClickListener не запускается из родительского класса
  • 0Как использовать сохраненные переменные, сохраненные в файле Javascript после перехода на новую страницу HTML?
  • 1JS Достижение и использование переменной родительского объекта
  • 1Выберите столбец из текстового файла с разделителями табуляции в Python и добавьте его в файл TSV
  • 0распределять набор элементов между N ведрами на основе весов
  • 1Как получить вывод из класса после ввода всех значений
  • 0C ++, оператор valgrind new (без знака int)
  • 0Невозможно отобразить детали JSON с помощью помощника руля
  • 0Предложение по реализации инструмента чтения файлов
  • 1Как сделать свойство установленным один раз и не может быть изменено?
  • 0C ++ Array функция и манипулирование
  • 0Javascript многопоточность обоих оконных фокусов
  • 1Преобразование различных категориальных переменных в фиктивные переменные
  • 0Один тест Угловой контроллер Карма-Жасмин работает, но не другой
  • 0Избавьтесь от случая переключателя, используя массив функторов
  • 0AngularJs: ng-bind не работает, когда я использую функцию в переменной и возвращаю некоторый текст
  • 0Отправить изображение на контроллер API с Angularjs
  • 0preg_replace несколько строк в скобках (php / regex)
  • 0php — проверка xml против xsd
  • 0Поддерживает ли $ templateCache предварительную загрузку изображений?
  • 0Случайный маркер на картах Google Jquery
  • 1Как принять Ctrl + Enter в качестве возврата при обработке события Enter для текстового поля в WPF?
  • 0как выбрать вариант на основе стоимости
  • 0HTML-форма без входного селектора в коде
  • 1Выделить только числовую часть выделения в одном регулярном выражении
  • 1Как добавить картинку в html-страницу в приложении Spring
  • 0Mysqldb не устанавливается в колбу Приложение использую pycharm
  • 1Проверка прослушивателя работает или нет
  • 0Необходимо запустить removeChild () дважды в Firefox
  • 1Как исправить первые три элемента массива (продолжайте отображаться как ноль)?
  • 0поймать ошибки / прочитать код состояния из вызова покоя — угловой
  • 0Поместите Div поверх видео, используя JavaScript
  • 0отправить массовое push-уведомление в GCM
  • 1Измените размер изображения так, чтобы оно соответствовало сетке JPanel
  • 0Можно ли избежать запроса в цикле?
  • 0Как настроить / etc / hosts в vagrant guest
  • 0Очистка хеш-таблицы в C ++
  • 0не может разобрать сериализованную строку json с идентификатором объекта mongo db, а также «»
  • 0Утечки памяти, когда мой код компилируется GCC
  • 1что-то похожее на приложение с несколькими рабочими столами
  • 1Получение «Неверная операция. Ошибка «Соединение закрыто» при попытке обновления oracle из программы на Visual C #
  • 0Нужна помощь с отображением ежемесячного платежа клиенту и оценкой HTML.
  • 1Ошибка преобразования при преобразовании значения varchar ‘Password’ в тип данных int [closed]
  • 0Как создать уникальную область видимости каждый раз, когда вызывается директива (AngularJS)

Сообщество Overcoder

  • Печать

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

Тема: Не работает библиотечная функция rand() в C++ на Ubuntu 16.04  (Прочитано 2394 раз)

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

Оффлайн
SNIKERSMRG

Добрый вечер.

Учусь программированию на С++ по книге «С++ Базовый курс. Третье издание» от Герберта Шилдта
Компилирую программы с помощью компилятора G++ (например g++ program81.cpp -o program81)


#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int magic;
int guess;

magic = RAND();

cout << "Введите свой вариант магического числа 1: ";
cin >> guess;

if(guess == magic)
{
cout <<"** Правильно **n";
cout << magic << "и есть то самое магическое число.n";
}
else
{
cout << "... Очень жаль но вы ошиблись.";
if (guess > magic)
   cout << "Ваш вариант ответа превышает магическое число.n";
else
cout << "Ваш вариант меньше магического числа.n";
      }
return 0;
}


В книге сказано что надо вводить строку magic = rand(); Но так рандом не работает, а программа думает что rand() это переменная.
В случае если писать в коде RAND() вместо rand() то при попытке скомпилировать программу получаем ошибку:

program22.cpp: In function ‘int main()’:
program22.cpp:10:14: error: ‘RAND’ was not declared in this scope magic = RAND();

А еще я раньше столкнулся с проблемой что в книге функция xor вводится маленькими буквами, но у меня так не работает, а работает только тогда, когда ввожу большими XOR

Скажите пожалуйста что не так ? Это особенность C++ на Linux или что ?

Notebook Samsung NP350V5C: 1366×768, Core i5 3210m, 6Gb Ram, 750Gb HDD, Radeon 7670m, Ubuntu 16.04


Оффлайн
aSmile

Поменял RAND на rand, у меня все собралось. Ubuntu 15.10, gcc 4.9

P.S. не забывай srand в начале


Оффлайн
soarin

Скажите пожалуйста что не так ? Это особенность C++ на Linux или что?

Нет, сам что-то не так делаешь.
Может копируешь код с криво оцифрованной книжки, где в слове rand значится русская буква ‘а’
Совет один — надо думать что пишешь и не лениться посмотреть и найти в поиски описание какой-то незнакомой функции

« Последнее редактирование: 04 Мая 2016, 07:18:04 от soarin »


  • Печать

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

Drakstar


  • #1

Всем привет) я создал простую арифметику (про чисел)… когда нажимаю проверка, то он мне показывает ошибку (вот только я не могу понять, как эту ошибку исправить)

135358623805.jpg

.. помогите!!!

rrrFer


  • #2

ты уверен что это не брэйкпоинт?

Drakstar


  • #3

Я делал это по уроку «видео» )) у всех работает

Drakstar


  • #4

Я как понял, что с++ не может прочитать библиотеку time

rrrFer


  • #5

ты код ошибки написал бы вместо скриншота.
Если кода ошибки нет — то убери брэйкпоинт )

Drakstar


  • #6

ты код ошибки написал бы вместо скриншота.
Если кода ошибки нет — то убери брэйкпоинт )

а можете обьяснить, что это «брэйкпоинт».. а то я новенький) и не знаю!!!

rrrFer


  • #7

ткни мышкой на красную точку слева (на картинке видно), если пропадет — то это оно — брэйкпоинт.

это точка останова, при запуске в режиме отладки программа останавливается на строке, в которой установлена точка останова.

Всегда прикладывай логи, а не картинки, если проблема с time — то в логах это будет написано — подключи «time.h».

Для srand нужен <cstdlib>, но не вижу подключил ты его или нет (картинка смазана).

Добавлено: вот смотри, кусочек программы:

//#include <cstring>
//#include <ctime>
int main() {
srand(time(0));
return 0;
}

компилятор сообщает об ошибках:

main.cpp: In function ‘int main()’:
main.cpp:5:15: error: ‘time’ was not declared in this scope
main.cpp:5:16: error: ‘srand’ was not declared in this scope
make[2]: *** [build/Release/MinGW-Windows/main.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

и мы сразу видим он не может найти функции time (15 символ 5 строки) и srand (16 символ 5 строки)

Если бы ты прикрепил такой лог-то тебе помогли бы сразу.

ЗЫ. выкинь свои видеокурсы и возьми нормальную книжку, ну или форум почитай, хотя бы.

Drakstar


  • #8

Спасибо тебе большое)) теперь буду знать!!!

rrrFer


  • #9

да пжалсто. Если есть страшное желание освоить С++ — пиши в аську, что-нибудь скину )

Drakstar


  • #10

А скажи пожалуйста, вот ты начинал учить с++ с чего?).. И получается ли у тебя!?… Вот я начал читать книгу, вот только низнаю, поможет ли )

rrrFer


  • #11

Drakstar
я начинал с большого количества олимпиадных задач.

На форуме куча тем с просьбами решить задачу. Можешь решать, мы покритикуем — узнаешь что-то новое )

Понравилась статья? Поделить с друзьями:
  • Error sharing violation
  • Error sqlstate hy000 2002 no such file or directory
  • Error shared module is not available for eager consumption
  • Error sqlstate 42s22 column not found 1054 unknown column
  • Error shader compilation failed check your log file for additional information ок