2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
1

Функции min/max/random

12.03.2011, 16:12. Показов 193552. Ответов 15
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
подключил библиотеку stdlib.h в программе хотел использовать функцию max написал

num3=max(num1,num2);

компилятор ругается на то что дескать "max это неопределенный идентификатор". так как написать эту функцию?
и ещё: хотел использовать функцию random написал (в другой программе не относящейся к первой проблеме)

num3=random(num1);

компилятор пишет мол "слишком много аргументов в вызове функции" но ведь я ему только один аргумент дал, как может быть слишком много аргументов?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
12.03.2011, 16:12
Ответы с готовыми решениями:

5х5 random массив В главной диагонали найти min и поменять местами max массива
4) 5х5 random массив. в главной диагонали найти min и поменять местами max массива. если одинаковые...

Найти max и min, если min левее max, то среднее арифметическое между ними
#include <iostream.h> #include <stdio.h> #include <conio.h> #include <math.h> void main() {...

Функции max min
не могу написать функцию для вычисления такого рода. Даны натуральные числа k, n, m,...

min, max функции.
Даны числа a(1), a(2), , a(2n). Вычислить: 1) max (a(1)+a(2n), a(2)+a(2n-1), , a(n)+a(n+1));и 2)...

15
Freelance
Эксперт С++
2891 / 1826 / 356
Регистрация: 09.09.2010
Сообщений: 3,841
12.03.2011, 16:15 2
Цитата Сообщение от MaxFX Посмотреть сообщение
num3=max(num1,num2);
Для этой функции надо подключать не stdlib.h, а algorithm.

Добавлено через 1 минуту
Цитата Сообщение от MaxFX Посмотреть сообщение
random
Не такой функции в стандарте.
1
Заблокирован
12.03.2011, 16:17 3
Пример на max
C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <algorithm>
using namespace std;
 
int main () {
  cout << "max(1,2)==" << max(1,2) << endl;
  cout << "max(2,1)==" << max(2,1) << endl;
  cout << "max('a','z')==" << max('a','z') << endl;
  cout << "max(3.14,2.72)==" << max(3.14,2.72) << endl;
  return 0;
}
Подробней: http://www.cplusplus.com/reference/algorithm/max/


Пример на rand

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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main ()
{
  int iSecret, iGuess;
 
  /* initialize random seed: */
  srand ( time(NULL) );
 
  /* generate secret number: */
  iSecret = rand() % 10 + 1;
 
  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);
 
  puts ("Congratulations!");
  return 0;
}
Подробней: http://www.cplusplus.com/refer... dlib/rand/
2
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12453 / 7478 / 1752
Регистрация: 25.07.2009
Сообщений: 13,748
12.03.2011, 16:37 4
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define RANDOM(a) (rand() % (a))
    
int main(void){
    int a, b;
    
    srand(time(NULL));
    
    a = RANDOM(100);
    b = RANDOM(100);
    
    printf("A = %d\nB = %d\nMAX = %d\nMIN = %d\n", a, b, MAX(a, b), MIN(a, b));
    
    return 0;
}
1
22 / 22 / 1
Регистрация: 29.01.2011
Сообщений: 84
12.03.2011, 19:15 5
Да ну нафиг у меня max всю жизнь в ioseream лежит
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12453 / 7478 / 1752
Регистрация: 25.07.2009
Сообщений: 13,748
12.03.2011, 19:46 6
Sumrak201007, круто! http://www.cplusplus.com/reference/algorithm/max/ и http://msdn.microsoft.com/en-u... bc7ya.aspx - не аргументы?
0
2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
13.03.2011, 12:45  [ТС] 7
так с random я разобрался. теперь осталось разобраться с max \ min я подключал следующие файлы:
C++
1
2
3
4
5
6
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
всё это не сделало погоды, компилятор по прежнему не распознает эти функции. меня сбивает с толку что в учебнике по которому я учусь написано что нужно лишь подключить stdlib.h и написать функцию следуйщим образом:

C++
1
maximum=max(a,b);
видимо я что то упустил из виду раз у меня это не работает. не думаю что в учебнике такая конкретная опечатка может быть...
из ответа IrineK'а мало что понял. что такое "cout << " и "<< endl;" ?

кто нибудь кому не трудно, напишите пожалуйста программу которая принимала бы 2 числа, с помощью функции определяла какое число больше, и выводила на экран то число которое больше. я попробую на практическом примере разобраться
0
2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
17.03.2011, 15:53  [ТС] 8
люди мне всё ещё нужна ваша помощь
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12453 / 7478 / 1752
Регистрация: 25.07.2009
Сообщений: 13,748
17.03.2011, 16:50 9
Цитата Сообщение от MaxFX Посмотреть сообщение
меня сбивает с толку что в учебнике по которому я учусь написано что нужно лишь подключить stdlib.h и написать функцию следуйщим образом:
Странный у Вас учебник. В мелкомягкой версии stdlib.h действительно присутствуют два макроса
C
1
2
3
4
/* Minimum and maximum macros */
 
#define __max(a,b)  (((a) > (b)) ? (a) : (b))
#define __min(a,b)  (((a) < (b)) ? (a) : (b))
но в целях переносимости их лучше не использовать. В конце концов две строчки написать, если нужно, не проблема.
2
2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
19.03.2011, 13:55  [ТС] 10
теперь это стало ясно. но у меня возник ещё вопросик: делал программу которая решает квадратные уравнения, писать пришлось в турбоси, в программе использовал функцию pow. в турбоси программа прошла компиляцию успешно и работала без проблем. в визуалс++ этаже программа тоже работала отлично. но вот когда попробовал написать вторую такую же программу в визулс++ то когда использовал функцию pow он кидал ошибку: "больше чем один случай перегруженной функции "pow" соответствует списку параметров". запустить программу через визуалс++ мне не удалось. зато в турбоси обе программы работают отлично. подскажите пожалуйста с чего вдруг визуалс++ не компилирует вторую программу? ведь обе программы написаны одинаково.
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12453 / 7478 / 1752
Регистрация: 25.07.2009
Сообщений: 13,748
19.03.2011, 14:20 11
Цитата Сообщение от MaxFX Посмотреть сообщение
обе программы написаны одинаково.
Хрустальный шар за шкаф закатился. Текст обоих программ выкладывайте.
0
2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
19.03.2011, 15:23  [ТС] 12
первая программа та которая работает и в турбоси и в визуалс++:

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
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <conio.h>
#include <math.h>
 
 
void main ()
 {  int inA, inB, inC, help1, help2, help3, X1, X2, count1=0, count2=0, count3=0, count4=0, cast;
    char V1;
 
 
    // inA/B/C: operators in the equation.
    // help1/2/3: helping operators.
    // X1/2: final solution of the equation.
    // count1: decides if the input is negative or positive
    // count2: counting the amount of pressing "enter" also it stops the loop
    // count3: counting the times that loop runs, also it decide to which
    //         variable each number belongs.
    // count4: counting the erorrs in input if this variable not equal to zero
    //         it means that input was wrong.
    // V1: variable that get the values from the user
    // cast: helping variable.
 
 
    clrscr () ;
    printf ("enter the numbers to the equation\n ax^2+bx+c\n");
 
    while (count2<3)
    {
    scanf ("%c", &V1);
    if (V1=='-') count1++, count4--;
    cast=(int)V1;
    if ((cast>=48) && (cast<=57))
    {   count3++;
        if (count3==1) inA=cast-48; if (count1=1) inA=inA*(-1);
        if (count3==2) inB=cast-48; if (count1=2) inB=inB*(-1);
        if (count3==3) inC=cast-48; if (count1=3) inC=inC*(-1);
    }
    else count4++;
    if (cast==10) count2++, count4--;
    }
 
    if (count4>0) printf ("wrong input");
    else
    {
 
 
 
 
 
                if (inA!=0)
                {
                help1=pow(inB,2);
                help2=4*inA*inC;
 
                help3=help1-help2;
                    if (help3 >= 0)
                    {
                        help1=sqrt(help3);
                        inB=inB*(-1);
                        X1=inB+help1;
                        X2=inB-help1;
 
                        inA=inA*2;
 
                        X1=X1/inA;
                        X2=X2/inA;
 
                        if (X1==X2)
                        {   printf ("this equation has only one solution: X=%d\n", X1);
                            if (X1>0) printf ("factorization of the equation is: (X-%d)(X-%d)", X1, X1);
                            else printf ("factorization of the equation is: (X+%d)(X+%d)", X1, X1);
                        }
                        else
                        {   printf ("this equation has two solutions: X1=%d  X2=%d\n", X1, X2);
                            if (X1>0)
                            {   if (X2>0) printf ("factorization of the equation is: (X-%d)(X-%d)", X1, X2);
                                else printf ("factorization of the equation is: (X-%d)(X+%d)", X1, X2);
                            }
                            else
                            {   if (X2>0) printf ("factorization of the equation is: (X+%d)(X-%d)", X1, X2);
                                else  printf ("factorization of the equation is: (X+%d)(X+%d)", X1, X2);
                            }
                        }
                    } // this line belongs to (help>0)
                    else printf ("this equation doesn't has solutions");
 
                } // this line belongs to (A==0)
                if (inA==0)
                {   X2=inC*(-1);
                    X1=X2/inB;
                    printf ("this is linear equation, the intersection points with the axess: (%d,0) ", X1);
                    printf ("(0,%d)", inC);
                }
    }
 
    getch () ;
 }

вторая программа которая работает только в турбоси

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include<stdio.h>
#include<conio.h>
#include<math.h>
 
void main ()
{   
    int count1=0, count2=0, count3=0, count4=0, iden=0, cast, op1, op2, op3, hv1, hv2, hv3, X1, X2;
    char inp, prin1=253, prin2=241;
 
    // count1: controls and stops the loop
    // count2: decides to which operator each input belongs
    // count3: decides if the input is positive or negative
    // count4: control the correction of the input, if this variable doesn't equal to zero it means
    //         that there is invalid input
    // iden: (identifier) allows to input two-figured numbers, by checking the sequence of input
    // cast: variable which saves the value that user has entered, after the casting
    // op1/2/3: (operator 1/2/3) operators of the equation which presents tha 'a', 'b' and 'c' parametrs
    // hv1/2/3: (Helping Variable) variables that help to solve a equation
    // X1/2: final solution/s of the equation
    // inp: (input) variable that gets values from the user
    // prin1/2: (print) variables which in general that are not necessary, but they allow to print the math symbols
 
 
    printf ("enter the numbers to this equation ax%c%cbx%cc\n", prin1, prin2, prin2);
    
 
    while (count1<3)
    {
        scanf ("%c", &inp);
        cast=(int)inp;
        if ((cast>=48) && (cast<=57))
        {   
 
            if (iden==1)
            {
                switch (count2)
                {   
                    case 1: if (count3!=1) op1=(op1*10)+(cast-48);
                            else op1=(op1*10)-(cast-48); break;
                    case 2: if (count3!=2) op2=(op2*10)+(cast-48);
                            else op2=(op2*10)-(cast-48); break;
                    case 3: if (count3!=3) op3=(op3*10)+(cast-48);
                            else op3=(op3*10)-(cast-48); break;
                }
            }
            else
            {
                count2++;
                switch (count2)
                {   
                    case 1: op1=cast-48; if (count3==1) op1=op1*(-1); break;
                    case 2: op2=cast-48; if (count3==2) op2=op2*(-1); break;
                    case 3: op3=cast-48; if (count3==3) op3=op3*(-1); break;
                }
                iden++;
            }
            
        }
        else count4++;
        if (cast==45)
        {
            switch (count2)
            {   
                case 0: count3=1; break;
                case 1: count3=2; break;
                case 2: count3=3; break;
                case 3: count3=4; break;
            }
        }
        if (cast==10) count1++, count4--, iden--;
        if (iden==3) iden=0;
    }
 
 
    if (op1!=0)
    {
        hv1=pow(op2,2); // вот тут визуалс++ постояно ругается на эту функцию
        hv2=4*op1*op3;
        hv3=hv1-hv2;
        if (hv3>=0)
        {
            X1=op2*(-1)+hv3;
            X2=op2*(-1)-hv3;
 
            X1=X1/(2*op1);
            X2=X2/(2*op1);
 
            if (X1==X2) 
            {   
                printf ("this equation has only one solution: X=%d\n", X1);
                if (X1>0) printf ("factorization of the equation is: (X-%d)(X-%d)\n", X1, X1);
                else printf ("factorization of the equation is: (X%d)(X%d)\n", X1, X1);
            }
            else
            {
                printf ("this equation has two solutions: X1=%d  X2=%d\n", X1, X2);
                if (X1>0)
                {   
                    if (X2>0) printf ("factorization of the equation is: (X-%d)(X-%d)\n", X1, X2);
                    else  printf ("factorization of the equation is: (X-%d)(X+%d)\n", X1, X2);
                }
                else
                {
                    if (X2>0) printf ("factorization of the equation is: (X+%d)(X-%d)\n", X1, X2);
                    else  printf ("factorization of the equation is: (X+%d)(X+%d)\n", X1, X2);
                }
 
            }
 
        }
    }
 
    printf ("OK");
    getch ();
}
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12453 / 7478 / 1752
Регистрация: 25.07.2009
Сообщений: 13,748
19.03.2011, 16:28 13
Цитата Сообщение от MaxFX Посмотреть сообщение
вторая программа которая работает только в турбоси
прекрасно откомпилировалось и gcc и cl, даже что-то вывело... единственное, что не понятно
Цитата Сообщение от MaxFX Посмотреть сообщение
char inp, prin1=253, prin2=241;
это что по задумке?
Функции min/max/random
0
2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
19.03.2011, 16:43  [ТС] 14
по задумке это лишние переменные суть которых вывести на экран квадратную функцию в таком виде:
ax²±bx±c в место: ax^2+bx+c сделано это просто так, без особого смысла.

что то я не понял. как вы запустили вторую программу через визуалс++? почему у вас она скомпилировалась а у меня нет?
Миниатюры
Функции min/max/random  
0
2 / 2 / 0
Регистрация: 22.10.2010
Сообщений: 37
21.03.2011, 10:29  [ТС] 15
вопрос остается открытым, я так и не разобрался почему у меня визуалс++ не хочет компилировать программу.
0
5 / 4 / 2
Регистрация: 16.08.2013
Сообщений: 41
25.08.2013, 12:59 16
Цитата Сообщение от IrineK Посмотреть сообщение
Пример на max
C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <algorithm>
using namespace std;
 
int main () {
  cout << "max(1,2)==" << max(1,2) << endl;
  cout << "max(2,1)==" << max(2,1) << endl;
  cout << "max('a','z')==" << max('a','z') << endl;
  cout << "max(3.14,2.72)==" << max(3.14,2.72) << endl;
  return 0;
}
Подробней: http://www.cplusplus.com/reference/algorithm/max/


Пример на rand

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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main ()
{
  int iSecret, iGuess;
 
  /* initialize random seed: */
  srand ( time(NULL) );
 
  /* generate secret number: */
  iSecret = rand() % 10 + 1;
 
  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);
 
  puts ("Congratulations!");
  return 0;
}
Подробней: http://www.cplusplus.com/refer... dlib/rand/
Второе это код С, а не С++
1
25.08.2013, 12:59
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.08.2013, 12:59
Помогаю со студенческими работами здесь

Функции max и min
Доброго времени суток) Как записать функции max и min? Сколько лазил, но понять не могу, как...

Функции min и max
Что делают функции min и max?И какие у них аргументы?

Ошибка функции max () | min()
Задача: Дано три числа, записанный в отдельных строках. Упорядочите их в порядке убывания....

Почему не возвращаются из функции min и max?
#include&lt;iostream&gt; #include&lt;stdlib.h&gt; #include&lt;time.h&gt; using namespace std; template &lt;class...


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

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru