- Печать
Страницы: [1] Вниз
Тема: Еще одна ошибка: генератор случайных (Прочитано 2182 раз)
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.
Вот я ввожу число 500 и дальше ничего не происходит.
Попробуйте угадать!
Вам дается не более 10 попыток
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>
вместо еретичного randomize !
srand( (unsigned)time( NULL ) ); //рандомчик
Если Wine — это костыль , то Punto Switcher — это протез , а Daemon Tools инвалидное кресло.

F1asher_086
#include <ctime>
вместо еретичного randomize !
srand( (unsigned)time( NULL ) ); //рандомчик
А куда нужно писать 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] Вверх
-
01-17-2009
#1
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?
-
01-17-2009
#2
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().
-
01-17-2009
#3
DESTINY
-
01-17-2009
#4
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
i got errors and i cant find out what they meant i have went down the program line by line trying to figure them out and i am having no success. I am trying to use call by call values and parametrers n this program. (list of errors are below)
|error: at this point in file|
error: a function-definition is not allowed here before ‘{‘ token|
|error: too many arguments to function `int rand()’|
error: extraneous `int’ ignored|
#include<iostream>
using namespace std;
v
oid score(int& ns1=0,int& ns2=2,int& ns3=3, int& ns4=4, int& ns5=5, int& n6=6, char gam_answ);
void display_score(int curr_score);
void roll_hold(int roll, int answer, int turn);
void turn_it_is();
void char play_again(char letter, char 'y', char 'n');
void int score(int& ns1, int& ns2, int&n s3, int& ns4, int& ns5, int& ns6, char gam_answ)
{
int turn;
while(char ns1=0)
{
cout << " next player " << ((turn % 2) ==1);
cout << " please select r for roll and h for hold ";
cin >> gam_answ;
gam_answ++;
}
}
void display_score(int curr_score)
{
int gam_answ;
curr_score = gam_answ++;
}
void roll_hold( char answer, int turn)
{
if(answer=='r')
{
do
{
(rand(turn)% (char& ns1=0,char& ns2=2,char& ns3=3, char& ns4=4, char& ns5=5, char& n6=6,)+1)));
}while(answer== 'r');
}
if (answer=='h')
{
do
{
system("pause");
}while (answer=='h');
}
void turn_it_is(int player1, int player2)
{ int ns1, ns2, ns3, ns4, ns5, ns6;
cout << (((turn_it_is%2)==1)?(player1:player2)<<
cout << " it's your turn ";
cin>> turn_it_is;
}
char play_again( char letter, char 'y', char 'n')
{
char 'y', 'n';
char letter ;
cout << " Would you like to play agian?( press y or n): ";
cin >> letter;
return letter;
}
i
nt main()
{
cout << "Race to 100 " << endl;
void score(char &ns1, char &ns2, char &ns3, char &ns4, char &ns5, char &ns6, char gam_answ);
void display_score(int curr_score);
void roll_hold(int roll, int answer, int turn);
void turn_it_is(int player1, int player2);
char play_again( char letter, char 'y', char 'n');
return 0;
}
0 / 0 / 0 Регистрация: 14.06.2021 Сообщений: 6 |
|
1 |
|
Положительные числа массива записать в массив В, а отрицательные – в массив С14.06.2021, 21:25. Показов 1752. Ответов 9
Разработать алгоритм и программу. Дан одномерный массив А, размерностью 1хn (2<=n<=20). Элементы массива принимают значения от 0 до 2000 и устанавливаются пользователем.
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
14.06.2021, 21:25 |
Ответы с готовыми решениями:
Все положительные элементы из массива записать в массив A, а отрицательные в массив B Из заданного массива C записать в массив А чётные положительные элементы, а в массив В нечётные отрицательные Записать в массив Y положительные, а в массив Z -отрицательные элементы массива 9 |
79 / 53 / 26 Регистрация: 08.09.2019 Сообщений: 141 |
|
14.06.2021, 21:50 |
2 |
Элементы массива принимают значения
0 |
BlackStoneBlack half-horse half-gateway 112 / 79 / 42 Регистрация: 10.05.2016 Сообщений: 517 |
||||
14.06.2021, 22:13 |
3 |
|||
Решение
1 |
0 / 0 / 0 Регистрация: 14.06.2021 Сообщений: 6 |
|
14.06.2021, 23:02 [ТС] |
4 |
выдаёт ошибки в программе
0 |
crazy duck 79 / 53 / 26 Регистрация: 08.09.2019 Сообщений: 141 |
||||
15.06.2021, 01:40 |
5 |
|||
1 |
0 / 0 / 0 Регистрация: 14.06.2021 Сообщений: 6 |
|
15.06.2021, 09:08 [ТС] |
6 |
9 17 [Error] too many arguments to function ‘int rand()’ Добавлено через 1 минуту
0 |
half-horse half-gateway 112 / 79 / 42 Регистрация: 10.05.2016 Сообщений: 517 |
|
16.06.2021, 14:03 |
7 |
crazy duck, у меня все работает, компилятор MinGW-64. На чем Вы программируете и чем собираете? Чувствую, это какой-нибудь. Visual Studio 2015 или старее.
1 |
79 / 53 / 26 Регистрация: 08.09.2019 Сообщений: 141 |
|
16.06.2021, 16:13 |
8 |
У меня все работает.
1 |
0 / 0 / 0 Регистрация: 14.06.2021 Сообщений: 6 |
|
20.06.2021, 10:20 [ТС] |
9 |
Спасибо, да на старье тестировалось, которое препод кинул Dev-Cpp называется. В https://www.onlinegdb.com. все отлично работает
0 |
7423 / 5018 / 2890 Регистрация: 18.12.2017 Сообщений: 15,694 |
|
20.06.2021, 12:14 |
10 |
все отлично работает возможно и работает, но по условию отрицательных в массиве нет. выше уже сообщалось:
Элементы массива принимают значения уточняйте условие задачи заодно выясните способ заполнения массива
Элементы массива … устанавливаются пользователем по формулировке больше похоже на ввод с клавиатуры
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
20.06.2021, 12:14 |
10 |
- Functions in C++
- the
too many arguments to function
Error in C++ - Resolve the
too many arguments to function
Error in C++ - Conclusion
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.
Срочно помогите с програмой на С++!!!
Показивает ошибку в 145 строке з rand, не могу понять чё, прога не работает! Пожалуйста очень нужно!!! Буду блогодарен.
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdlib.h>
using namespace std;
class Massiv
{
int *a,*b,n,min;
public:
void Sozd();
void Vvod_Sl();
void Form(int n1, int n2);
void Form_2(int n3, int n4);
void Print();
void Print_2(int number);
void Print_3(int rec, int field);
};
int main()
{
Massiv a,b;
int number,punkt,rec,field,kol,n1,n2,n,n3,n4;
system(«cls»);
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt;
while (punkt!=7)
{
switch(punkt)
{
case 1: {rand(); //sozdanie massiva
a.Vvod_Sl();
cout<<endl;
a.Print();
cout<<endl;
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt;
}
break;
case 2: {a.Print(); //pechat massiva
cout<<endl;
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt; }
break;
case 3: { //pechat stroki po indeksu
cout<<«Vvedite nomer massiva (numeracia s 0!): «;cin>>number;
cout<<endl;
a.Print_2(number);
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt;
}
break;
case 4: { //sceplenie dvuh massivov
cout<<«Vvrdite nomer 1-go massiva(numeracia s 0!): «;cin>>n1;cout<<endl;
cout<<«Vvedite nomer 2-go massiva(numeracia s 0!): «;cin>>n2;cout<<endl;
a.Form(n1,n2);
cout<<endl;
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt;}
break;
case 5: { //sliyanie dvuh massivov
cout<<«Vvrdite nomer 1-go massiva(numeracia s 0!): «;cin>>n3;cout<<endl;
cout<<«Vvedite nomer 2-go massiva(numeracia s 0!): «;cin>>n4;cout<<endl;
a.Form_2(n3,n4);
cout<<endl;
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt;}
break;
case 6: { //pechat konkretnogo elementa konkretnoi stroki
cout<<«Vvedite nomer stroki massiva(numeraciya s 0!): «;cin>>rec;
cout<<endl;
cout<<«Vvedite nomer stolbca: «;cin>>field;
cout<<endl;
a.Print_3(rec,field);
cout<<«1 — sozdanie massiva»;cout<<endl;
cout<<«2 — pechat vseh strok»;cout<<endl;
cout<<«3 — pechat stroki po indeksu»;cout<<endl;
cout<<«4 — sceplenie dvuh massivov»;cout<<endl;
cout<<«5 — sliyanie dvuh massivov»;cout<<endl;
cout<<«6 — pechat konkretnogo elementa konkretnoi stroki»;cout<<endl;
cout<<«7 — vihod»;cout<<endl;
cout<<«Vvedite punkt menu «; cin>> punkt;}
break;
case 7:
break;
}
}
}
void Massiv :: Sozd()
{
int m;
cout<<«kolvo strok?»;cin>>n;
int min=0;
for (int i=0;i<n;i++)
{
cout<<«kolvo elementov v «<< i+1 <<» stroke?»;cin>>m;
*(b+i)=m;
if (min<m) min=m;
}
a=(int*)malloc(sizeof(int)*n*min);
}
void Massiv::Vvod_Sl()
{
Sozd();
for(int i=0;i<n;i++)
for (int j=0; j<*(b+i); j++)
{
*(a+i+j)=-20+rand(41);
}
}
void Massiv :: Print()
{
for(int i=0;i<n;i++)
{
for (int j=0; j<*(b+i);j++)
{
cout<<setw(6)<<*(a+i+j);
}
cout<<endl;
}
}
void Massiv :: Print_2(int number)
{
for(int i=0;i<n;i++)
{
for (int j=0; j<*(b+i);j++)
{
if (i==number) cout<<setw(6)<<*(a+i+j);
}
cout<<endl;
}
}
void Massiv :: Print_3(int rec, int field)
{
for(int i=0;i<n;i++)
{
for (int j=0; j<*(b+i);j++)
{
if ((i==rec)&&(j==field)) cout<<«Danii element= «<<setw(6)<<*(a+i+j);
else «Massiv s takimi dannimi ne naiden!»;
}
cout<<endl;
}
}
void Massiv :: Form(int n1,int n2)
{
int m1,m2,k,j,l,p;
int c[20];
//zapominaem kolvo elementov v strokah
m1=*(b+n1);
m2=*(b+n2);
// *(b+n1)=m1+m2;
int m3=m1+m2;
k=0;
for (l=0;l<m3;l++)
if(l<m1)
{c[l]=*(a+n1+l);
cout<<setw(6)<<c[l];
}
else if((l>=m1)&&(l<m3))
{
c[l]=*(a+n2+k);
cout<<setw(6)<<c[l];
k++;
}
}
void Massiv :: Form_2(int n3,int n4)
{
int m1,m2,k,j,l,p,l1;
int c[20],f[20];
//zapominaem kolvo elementov v strokah
m1=*(b+n3);
m2=*(b+n4);
int m3=m1+m2;
k=0;
for (l=0;l<m3;l++)
{
if(l<m1)
{c[l]=*(a+n3+l);
}
else if((l>=m1)&&(l<m3))
{
c[l]=*(a+n4+k);
k++;
}
}
l1=0;
f[l1]=c[l1];
cout<<setw(6)<<f[l1];
//sliyanie
for(p=1;p<m3;p++)
if(f[l1]!=c[p])
{ l++;
f[l1]=c[p];
cout<<setw(6)<<f[l1];
}
}