Error too many arguments to function long int random

Решил сделать отдельную тему, т.к. в предыдущей развернулся не маленький спор.
  • Печать

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

Тема: Еще одна ошибка: генератор случайных  (Прочитано 2183 раз)

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

Оффлайн
F1asher_086

Решил сделать отдельную тему, т.к. в предыдущей развернулся не маленький спор. Не буду мешать.

Так вот, у меня такая проблема: не каким боком не хочет генерировать число. В книге такой пример:

#include <iostream>
#include <stdlib.h>
// Программа-игра "Угадай число"
using namespace std;
int main()
{ cout << "Задумано число от 1 до 1000." << endl;
cout << "Попробуйте угадать!" << endl;
cout << "Вам дается не более 10 попыток" << endl;
const int n = 10; // Максимальное число попыток
randomize();                            // Инициализация датчика случайных чисел
unsigned int number = random(1000) + 1; // Случайное число
unsigned getnum; // Получаемое число от пользователя
int i = 0;
while (i < n);
{ cout << "Какое число задумано?" << endl;
cin >> getnum;
++i; // Считаем количество попыток
if (number < getnum) cout << "Задуманное число меньше!n";
if (number > getnum) cout << "Задуманное число больше!n";
if (number == getnum)
{ cout << "Вы угадали!!!n";
cout << "Сделано " << i << " попыток.n";
return 0; // Завершение с успехом
}
}
cout << "Вы исчерпали все попытки! Жаль."<< number << endl;
return -1; // Завершение с неудачей
}
Компилятор говорит:

~$ g++ -o '/home/test/random_igra' '/home/test/random_igra.cpp'
/home/test/random_igra.cpp: В функции «int main()»:
/home/test/random_igra.cpp:8:12: ошибка: нет декларации «randomize» в этой области видимости
/home/test/random_igra.cpp:9:35: ошибка: too many arguments to function «long int random()»
/usr/include/stdlib.h:327:17: замечание: declared here

Перечитал много разных статей и тем на форумах,

но так и не нашел решения. с функцией rand() программа успешно компилируется, но когда доходит до ввода предполагаемого числа, программа его не проверяет и не выводит сообщений.

~$ /home/test/random_igraЗадумано число от 1 до 1000.
Попробуйте угадать!
Вам дается не более 10 попыток
500
Вот я ввожу число 500 и дальше ничего не происходит.

Что с этим делать?

« Последнее редактирование: 16 Мая 2012, 21:14:59 от yorik1984 »


Оффлайн
Señor_Gaga

/home/test/random_igra.cpp:8:12: ошибка: нет декларации «randomize» в этой области видимости

Судя по этому сообщению не хватает библиотеки где прописана функция randomize()
Давно не писал, но возможно надо #include <math.h>


Оффлайн
F1asher_086

Señor_Gaga,
Не помогает, та же ошибка.


Оффлайн
victor00000


Оффлайн
Zeka13

#include <ctime>
srand( (unsigned)time( NULL ) ); //рандомчик
вместо еретичного randomize !

Если Wine — это костыль , то  Punto Switcher — это протез , а Daemon Tools инвалидное кресло.


Оффлайн
F1asher_086

#include <ctime>
srand( (unsigned)time( NULL ) ); //рандомчик
вместо еретичного randomize !

А куда нужно писать srand( (unsigned)time( NULL ) ), сразу после включения ctime? Если так, то у меня выдает ошибку:

~$ g++ -o '/home/test/random_igra' '/home/test/random_igra.cpp'
/home/test/random_igra.cpp:5:7: ошибка: expected constructor, destructor, or type conversion before «(» token
/home/test/random_igra.cpp: В функции «int main()»:
/home/test/random_igra.cpp:13:35: ошибка: too many arguments to function «long int random()»
/usr/include/stdlib.h:327:17: замечание: declared here


Оффлайн
Señor_Gaga

Уже давно было бы проще написать собственный генератор случайных чисел (3-4 строки кода).


Оффлайн
Yurror

Señor_Gaga,
расскажи это людям защищавшим диссертации по генерации случайных чисел =)
не самая тривиальная задача нынче воспринимаемая как должное


Оффлайн
Señor_Gaga

Вот простейший генератор на C


 unsigned long next=1;

   int rand(void) { /* возвращает псевдослучайное число */
    next=next*1103515245+12345;
   return((unsigned int)(next/65536)%32768);
 }

   void srand(unsigned int seed) {  next=seed;  }

« Последнее редактирование: 17 Мая 2012, 10:20:17 от Señor_Gaga »


Оффлайн
Zeka13

используйте google и книге, ну или мне в личку можно написать

Если Wine — это костыль , то  Punto Switcher — это протез , а Daemon Tools инвалидное кресло.


  • Печать

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

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • c++ random.h compiling issue

  1. c++ random.h compiling issue

    Hello, all. I’ve joined a programming class in my high school, and the book they give us is 1. Old and 2. Is written for some common Windows compiler. So, obviously, I’m having some issues =/ The most recent one I can find NO fixes for is an issue with trying to use random.h. So originally my code went:
    #include <iostream>
    #include <random>

    PHP Code:


    #include <iostream>

    #include <random>

    using namespace std;
    int main() {

      for (
    int i=1i<=10i++)

        
    cout << random(100) << endl;





    I just compiled with «g++ random.cpp», and I got a TON of errors, almost all of which came from /usr/include/c++/4.3/tr1_impl/random.tcc. After a little bit of searching and some trial and error, I tried the following:

    PHP Code:


    #include <iostream>

    #include <cstdlib>
    int main() {

      for (
    int i=1i<=10i++)

        
    std::cout << random(100) << std::endl;





    This only generated a few errors, so I figured it was closer to the «right» code.

    Code:

    /usr/include/stdlib.h: In function �int main()�:
    /usr/include/stdlib.h:327: error: too many arguments to function �long int ran
    dom()�                                                                       
    randoms.cpp:6: error: at this point in file

    Can anyone shed some light on this issue for me? Thanks in advance!


  2. Re: c++ random.h compiling issue

    Random (AFAIK) is not a standard header in either C or C++. In the stdlib.h (or cstdlib) headers, there is a random function that takes no arguments and returns a long int. My guess is that you have some header in your program that defines a random function taking an integer argument (maybe random.h) and that you are not including it. Else, the code is dependant on an specific compiler. If that is the case, ask what the semantics of the random function are and check how you can adapt. Knowing what the windows compiler is can help finding docs on that matter.

    At any rate, the compiler is only seeing the ‘long random()’ function definition in stdlib.h and it is complaining about you passing an argument the function does not have.


  3. Re: c++ random.h compiling issue

    Random will be a standard header in the next version of C++, C++0x, and it is already available as a part of the Technical Report 1 (TR1). However, the procedure for including TR1 files differs between compilers. In g++, if you want the random file from tr1, you have to include tr1/random instead of just random. If you don’t, libstdc++ interprets that you want C++0x support, which has to be explicitly enabled with -std=c++0x.

    May the Source be with you.


  4. Re: c++ random.h compiling issue

    I am assuming the OP is not dealing with the C++0x random header for two main reasons: it is stated in the question that the book is old and there is no random(int) function in the C++0x random header. That header provides many random number generators written as templated classes, and the OP code would not compile against those headers either. It looks more like either user code or a vendor extension.


  5. Re: c++ random.h compiling issue

    PHP Code:


    #include <iostream>
    #include <cstdlib>
    using namespace std;int main()
    {       
    int ia[100], n;cout << "n="cin >> n;
            
    srand(time(0)); // randomize
            
    for(0i<n; ++i)
                    
    a[i] = rand()%100//random from 0 to 99
            
    for(0i<n; ++i
                    
    cout << a[i] << ' ';

            return 

    0;




    Take a look at rand and srand @ http://www.cplusplus.com/reference/clibrary/cstdlib/ && http://members.cox.net/srice1/random/crandom.html

    Last edited by Wistful; December 11th, 2009 at 01:25 AM.


Tags for this Thread

Bookmarks

Bookmarks


Posting Permissions

  1. 01-17-2009


    #1

    karfes is offline


    Registered User


    too many arguments

    am a beginer in C and
    i wanted to use’rand()’ to generate random numbers, so i wrote the simple program:

    Code:

    //libraries
    #include <stdio.h> /*defines scanf() and printf()*/
    #include <stdlib.h> //defines rand()
    #include <time.h> //defines time() and is needed for randomize()
    
    
    
    //main
    int main()
    {
        //declaring a variable
        int n;
    	randomize();
        n = rand(100);
    
        //display result
        printf("nRandom numbers in the range 0-99");
    printf("%d",n);
    
       //wait for a key to be pressed by user before program exits
    getch();
    
        }//end main

    but wen i compile i get a «too many arguments to function ‘rand’ » error. why is this?


  2. 01-17-2009


    #2

    grumpy is offline


    Registered User


    rand() accepts no arguments, and returns a single value. You’ve called it with one argument. Hence the error.

    Incidentally, call randomize() once and then call rand() multiple times (eg in a loop).

    There’s also the incidental concern that randomize() is windows-specific. If you care about portability, use srand().


  3. 01-17-2009


    #3

    BEN10 is offline


    DESTINY

    BEN10's Avatar



  4. 01-17-2009


    #4

    karfes is offline


    Registered User


    i got it. i used:

    Code:

    #include <stdio.h> 
    #include <stdlib.h>
    #include <time.h> 
     
    //main
    int main (int argc, char *argv[])
    {
                /* Simple "srand()" seed: just use "time()" */
                unsigned int iseed = (unsigned int)time(NULL);
                srand (iseed);
    
               /* Now generate 5 pseudo-random numbers */
               int i;
               for (i=0; i<5; i++)
               {
                printf ("rand[%d]= %un",
                i, rand ());
            }
      return 0;
    }//end main

    and the output was:
    rand[0]= 1626340950
    rand[1]= 859402563
    rand[2]= 444565884
    rand[3]= 1614271775
    rand[4]= 403955761
    thanx, especially for the cross platform advice


  1. Functions in C++
  2. the too many arguments to function Error in C++
  3. Resolve the too many arguments to function Error in C++
  4. Conclusion

Too Many Arguments to Function Error in C++

We encounter a lot of errors while writing a piece of code. Solving errors is one of the most crucial parts of programming.

This article will discuss one error we encounter in C++: too many arguments to function.

Functions in C++

The too many arguments to function is an error in C++ that we encounter when we specify different arguments in the declaration and the implementation of a function.

To understand this error and fix it, we should first discuss what functions are.

A function is a block of code that is reusable and is used to perform repetitive tasks. Suppose we want to print "Hello World" in a program five times.

Now, one way to do so is to write the print statement every time we want to print it, whereas the other efficient way would be to make a function where the code to write "Hello World" would be written, and this function would be called whenever we need it.

The function that prints "Hello World" will be implemented below.

#include <iostream>
using namespace std;
void print();
int main() {
	print();
	print();
	print();
	print();
	return 0;
}
void print(){
    cout<<"Hello World"<<endl;
}

Output:

Hello World
Hello World
Hello World
Hello World

However, if we write the print() function after the main(), then we need to first declare the function before the main() so that the compiler knows that a function named print() exists in the program.

the too many arguments to function Error in C++

Arguments are values that are defined when a function is called. The too many arguments to function error occur because of these arguments in a function.

The number of arguments should be the same in the function call and the function declaration of a program. We get this error when the number of arguments is different in the function declaration and function call.

Let us see a code to depict what these different arguments mean. Below is the code snippet that throws an error stating that there are too many arguments in a function.

#include <iostream>
using namespace std;

void addition();

int main() {
	addition(4,5);
	return 0;
}

void addition(int a, int b){
    cout<<"Addition of the numbers "<< a<< " and " << b <<" = " << (a+b)<<endl;
}

Output:

./6e359960-d9d7-4843-86c0-b9394abfab38.cpp: In function 'int main)':
./6e359960-d9d7-4843-86c0-b9394abfab38.cpp:7:14: error: too many arguments to function 'void addition)'
  addition4,5);
              ^
./6e359960-d9d7-4843-86c0-b9394abfab38.cpp:4:6: note: declared here
 void addition);
      ^

In the above code snippet, we have used the function addition() to add the two numbers. On the third line, we have declared the function addition() with no arguments (arguments are present in the parentheses of a function).

However, when we make or define the addition() function, we have passed two arguments, a and b, to it so that these two numbers can be added. Therefore, this mismatch in the number of arguments causes the too many arguments to function.

Resolve the too many arguments to function Error in C++

The too many arguments to function error in C++ can be resolved by considering the number of arguments passed to the function when declaring and defining it.

Let us take the same example as above and resolve its error.

#include <iostream>
using namespace std;
void addition(int,int);
int main() {
	addition(4,5);
	return 0;
}
void addition(int a, int b){
    cout<<"Addition of the numbers "<< a<< " and " << b <<" = " << (a+b)<<endl;
}

Output:

Addition of the numbers 4 and 5 = 9

Therefore, as you can see, the error has been removed, and our result of adding two numbers has been displayed successfully. We have just added the two int types to the declaration of the function on the 3rd line.

This way, before encountering the addition() function, the compiler knows that an addition() function exists in our program that will take arguments in it.

Conclusion

This article has discussed too many arguments to function. We have discussed functions briefly, how this error occurs in the C++ program and how to resolve the same.

However, the main thing while resolving this error would be that there should be the same number of arguments wherever the function is defined or declared.

Понравилась статья? Поделить с друзьями:
  • Error tokenizing data c error expected 10 fields in line 6044 saw 11
  • Error tokenizing data c error expected 1 fields in line 28 saw 367
  • Error tokenizing data c error eof inside string starting at row
  • Error tokenizing data c error calling read nbytes on source failed try engine python
  • Error tofixed is not a function