Srand time null ошибка

@steelhouse, Вы хотя бы пишите, какой компилятор, ОС и что именно не работает. В Вашем случае (в линуксе), просто компилится (конечно, с флагом -std=c99 или gnu99) с предупреждениями, а дальше вполне себе работает, печатает единички и двойки. — А для компиляции без warnings добавьте, как уже говорили, time.h и возвращаемый main() тип int.

– avp

11 апр 2013 в 11:38

; at the end of the #include directives are the problem in your code. #include directives don’t need (wrong to place indeed) semicolons at the end unlike C++ statements.

[Warning] extra tokens at end of #include directive [enabled by default] 

It seems any character after > in the directive causes this error/warning.

          #include<iostream>a   //error

Change to this:

#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;


class Problem3 {
    public:
        bool isPrime(long double num) {
            srand(time(NULL));
            return 0;
        }
};

int main(){
    cout<<"Hello Main";
}

EDIT:

Regarding the linker issue:

One suggestion is C++ expects types to be explicitly casted between types (more than C). So, use a cast to convert time_t which is returned by the time to unsigned int which is the input parameter type of srand. (And of course this might not be the problem with linker error)

Instead of using stdlib.h, try using <cstdlib>, try if it helps. Because it uses namespace.

Apart from that, I have seen this snippet here. Use that pattern if it helps.

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main() 
{
    srand(time(0)); //use current time as seed for random generator
    int random_variable = rand();
    cout << "Random value on [0 " << RAND_MAX << "]: " 
              << random_variable << 'n';
}

there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++

Never use time() to initialize srand()..

EDIT:

Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function ‘isdigit’ could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.

Quoted from that question:

I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make «Function could not be
resolved» be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the «missing» functions are in symlinked include files. Would
love any input on this theory.

Hope that points to solve the problem.

Matroskin2

1 / 1 / 0

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

Сообщений: 7

1

24.02.2020, 22:12. Показов 6601. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Помогите. Компилятор выдает предупреждение :
Domm 5.1.cpp(11,15): warning C4244: ‘argument’: conversion from ‘time_t’ to ‘unsigned int’, possible loss of data

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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
 
int main()
{
    srand(time(NULL));
    const int n = 20;
    int a[n];
    for (int i = 0; i < n; i++) {
        a[i] = rand() % 100;
        cout << a[i] << " ";
    }
    cout << endl;
    int is, c;
    do {
        is = 0;
        for (int i = 1; i < n; i++)
            if (a[i - 1] > a[i])
            {
                c = a[i];
                a[i] = a[i - 1];
                a[i - 1] = c;
                is = 1;
            };
    } while (is);
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
}



0



Yetty

7427 / 5021 / 2891

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

Сообщений: 15,694

24.02.2020, 22:17

2

Matroskin2, пишите так:

C++
1
srand((unsigned)time(0));



1



1 / 1 / 0

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

Сообщений: 7

24.02.2020, 22:23

 [ТС]

3

С чем это связано? Я писал по методичке ну и в нете есть такие примеры как у меня .



0



hoggy

Эксперт С++

8725 / 4305 / 958

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

Сообщений: 9,752

24.02.2020, 22:35

4

Цитата
Сообщение от Yetty
Посмотреть сообщение

srand((unsigned)time(0));

Код

warning: use of old-style cast [-Wold-style-cast]

Цитата
Сообщение от Matroskin2
Посмотреть сообщение

С чем это связано?

методички пишут такие же балбесы,
как и большинство авторов примеров из интернет.

я пишут вот так:

C++
1
2
3
    ::std::srand(
        static_cast<unsigned>( ::std::time(0) )
    );



1



2549 / 1208 / 358

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

Сообщений: 3,826

24.02.2020, 23:49

5

Добрый вечер, hoggy, а зачем перед std «::» ?

Нету ли тут избыточности по типу int _count = 0; // количество



0



Эксперт С++

8725 / 4305 / 958

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

Сообщений: 9,752

25.02.2020, 00:00

6

Цитата
Сообщение от rikimaru2013
Посмотреть сообщение

а зачем перед std»::» ?

оптимизация поиска имён.

помогает тормозным и глупым

Visual Studio

IDE чутка быстрее ориентироваться в коде.



1



Croessmah

Неэпический

17815 / 10586 / 2044

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

Сообщений: 26,627

Записей в блоге: 1

25.02.2020, 00:12

7

rikimaru2013, а еще язык c++ прекрасен

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
#include <iostream>
#include <cstdlib>
#include <ctime>
 
namespace some {
    namespace std {
        int time(int *) {
            return 0;
        }
        void srand(int) {
            ::std::cout << "yeah!n";
        }
    }
    
    void bar() {
        std::srand(time(0)); //x::std::srand
        ::std::srand(time(0));//::std::srand
    }
}
 
 
int main()
{
    some::bar();
}



1



4023 / 3280 / 920

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

Сообщений: 12,266

Записей в блоге: 1

25.02.2020, 01:13

8

Цитата
Сообщение от Matroskin2
Посмотреть сообщение

С чем это связано? Я писал по методичке ну и в нете есть такие примеры как у меня .

и что тебя смущает? warning это не ошибка



0



Member Avatar

12 Years Ago

I can’t figure out why I am getting this error. I have tried #include several things and I have tried changing the location of srand.

#include <iostream.h>
#include <ctime>



class Horse {


    int position;
    public:
    Horse();                    //Horse constructor??? Per UML
    int random;
    srand( time(0));
    void advance(){
        random = rand() % 2;
        cout << random;
    }//end advance function

    int getPosition(int y){

    return y;
    }//end getPosition function


};//end Horse class

Edited

10 Years Ago
by Nick Evan because:

Fixed formatting


Recommended Answers

I haven’t dealt with classes yet, but i would assume you’d have to place it inside the function. Have you tried ?

Jump to Post

All 3 Replies

Member Avatar


Crutoy

0



Junior Poster in Training


12 Years Ago

I haven’t dealt with classes yet, but i would assume you’d have to place it inside the function. Have you tried ?

Member Avatar


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster


12 Years Ago

you can not put function calls in class declaration unless they are inside inline code. Move that srand() line to main()

int main()
{
   srand(time(0));
}

Depending on the compiler you are using you may have to typecase time() to unsigned int instead of time_t.

Member Avatar


sfuo

111



Practically a Master Poster


12 Years Ago

A class is made up of functions and variables so you can not randomly throw in a function call like srand() unless it is within one of it’s own functions. I would call srand() at the top of your main() function.

#include <iostream> //use iostream not iostream.h (.h is the c version)
#include <ctime>
using namespace std;

class Horse
{
	int position;
	int random;

	public:

	Horse(){}; //note the two curly brackets (this is the default constructor that is made if you do not include a constructor)

	void advance()
	{
		random = rand() % 2;
		cout << random;
	}

	int getPosition( int y )
	{
		return y;
	}

};

int main()
{
	srand(time(0));//seed your random here.
	Horse test;
	test.advance();

	return 0;
}


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • srand(time(NULL)) error message

  1. srand(time(NULL)) error message

    Hi
    I’m not a programmer, but I want to get some C code to work for some study that I’m doing in cognitive psychology. It’s a mathematical model; it does a calculation and returns a value. The code was written in 1996, and when I try to compile it (I’m typing gcc filename), I get a number of error messages. The main one relates to the random number generator.
    The original code was:

    Code:

     #include "ran1.c"
    /* random seed */
    long     IDUM    = -3;

    I have replaced only the first line with:

    Code:

    #include <time.h>
    
    srand(time(NULL));
    int r = rand();

    but I get this message:

    Code:

    43:7: error: expected declaration specifiers or �...� before �time�
    
    44:1: error: initialiser element is not constant

    I think I’m heading in the right direction, but I don’t know enough about programming to get it right. I really don’t want it to return the wrong value.
    Any help would be appreciated. Thank you.


  2. Re: srand(time(NULL)) error message

    It would be immensely helpful to see the actual implementation you have versus a snip of code as you have provided.

    A simple example of using srand() and rand() would be something like:

    Code:

    #include <stdlib.h>
    #include <time.h>
    
    const unsigned int MAX_NUM = 1000;
    
    int main()
    {
        srand(time(NULL));
    
        unsigned int num = rand() % MAX_NUM;   // num can range from 0 through (MAX_NUM - 1)
    }


  3. Re: srand(time(NULL)) error message

    Just a note of caution about PRNGs — based on the name (ran1.c) and the negative-long seed (IDUM) it looks like you are trying to replace the Numerical Recipes implementation? If so, that’s a long-period floating point PRNG — depending what your model is doing (and how many times it’s doing it) the system rand() may or may not be a suitable replacement.


  4. Re: srand(time(NULL)) error message

    Thanks for your helpful comments. Any information I can gather is helpful.

    Quote Originally Posted by dwhitney67
    View Post

    It would be immensely helpful to see the actual implementation you have versus a snip of code as you have provided.

    Does this make it clearer?
    model.txt
    The attached model.txt file is the C code that I think might be relevant. I’ve just killed about 2/3 of the lines from the middle of the file.

    Just to recap, when I tried to compile this, I got an error message in relation to the random generator.
    Thank you.

    Last edited by lisati; March 9th, 2013 at 04:34 AM.

    Reason: Change HTML tags to QUOTE


  5. Re: srand(time(NULL)) error message

    Is there any particular reason you need to replace the original Numerical Recipes ran1 implementation? The license terms are not onerous afaik

    http://apps.nrbook.com/c/index.html

    I’d suggest including the necessary declarations and compiling the ran1.c file separately rather than doing #include «ran1.c» though


  6. Re: srand(time(NULL)) error message

    ok, Thanks again.

    Code:

    rip@Duck:/media/win/arjuna/current_study$ gcc memnew.c
    memnew.c:22:18: fatal error: ran1.c: No such file or directory
    compilation terminated.

    Maybe I need to install something. This is Xubuntu Precise.


  7. Re: srand(time(NULL)) error message

    If it’s the routine I think it is, you would need to get it from Numerical Recipes

    If you buy the book, you can just type it in (it’s only ~ 50 lines of code) — or you can get an electronic subscription

    http://www.nr.com/aboutNR3electronic.html


  8. Re: srand(time(NULL)) error message


  9. ran1.c includes base.h

    The code I have ran1.c includes:
    Where do I look for that?
    Am I on the right track?

    I’d suggest including the necessary declarations and compiling the ran1.c file separately rather than doing #include «ran1.c» though

    I’m not sure what the necessary declarations are. I’m very low level here. As I say, I’m interested in a mathematical model in cognitive psychology, I’m not a programmer.
    Thanks again.


  10. error in fprintf: should be struct

    Hello
    I’m asking for help with format in C. The code has this line:

    Code:

     fprintf( OUTD , "%s" , SPARAM[ i ] );

    And the error is:

    HTML Code:

    format �%s� expects argument of type �char *�, but argument 3 has type �struct PARAM� [-Wformat]

    And I think you might need to know this:

    Code:

    /* strings used by the program */
    #define  NPARAM 12
    struct PARAM
    {
      char *word;
    } SPARAM[ NPARAM ] =
    {
      "Length          ",
      "Strength        ",
      "Frequency       ",
      "Criterion Used  ",
      "Criterion ROC   ",

    I’ve cut it short here, but I think that’s enough.

    I can see what the problem is, but my programming ability is very low level, and I have no idea about C. I need to change the «%s», right?
    I need to get this old C code working. Fortunately, I’ve had some good help here, and this is the only error message left.
    Comments gratefully received.


Tags for this Thread

Bookmarks

Bookmarks


Posting Permissions

Понравилась статья? Поделить с друзьями:
  • Sr1960 ошибка fanuc
  • Sr1938 фанук ошибка
  • Sr0002 tv ошибка fanuc
  • Squirrel газовая колонка ошибка е4 решение
  • Squid изменить сообщение об ошибке