Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/5: Рейтинг темы: голосов - 5, средняя оценка - 4.60
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52

Нарушение прав доступа при чтении

16.07.2013, 10:28. Показов 1041. Ответов 15
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте. Собственно проблема вот в чем при вызове функции нахождения определителя выскакивает ошибка Необработанное исключение в "0x77bf15ee" в "Programming of linear algebra problems.exe": 0xC0000005: Нарушение прав доступа при чтении "0xcdcdcdd5". Помогите понять в чем причина и исправить код.
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include "stdafx.h"
 
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include <cmath>
 
short int index = 0;
double det = 0;
bool index_bool = false;
 
void Enter__Array ( double ** &, const short int & );
void Output_Array ( double ** &, const short int & );
void Check__Zeros   ( double ** &, const short int &, short int *, bool * );
double Determinant  ( double ** &, const short int &, short int *, bool * );
double ** & Matrix_Minor ( double ** &, const short int &, short int, short int );
 
int _tmain(int argc, _TCHAR* argv[])
{
    setlocale (LC_ALL,"RUSSIAN");
    short int size;
        std::cin >> size;
    double ** Matrix_A = new double * [ size ];
    for ( int i = 1; i <= size; i ++ )
        Matrix_A [i] = new double [ size ];
    Enter__Array (  Matrix_A, size );
    printf ( "\n%3s", " Матрица А \n\n" );
    Output_Array (  Matrix_A, size );
    det = Determinant (  Matrix_A, size, & index, & index_bool );
    printf ("\n%3G", det );
    _getch ();
    return 0;
}
/*___________ Вычисление определителя матрицы ______________________*/
 
double Determinant ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    double determinant = 0;
    if ( size == 1 ) return Matrix [0][0];
    else
    {
        Check__Zeros ( Matrix, size, & index, & index_bool );
        if ( * index_check )
        {
            for ( int i = 1; i <= size; i ++ )
            {
                if ( Matrix [ * index_number ] [i] == 0 ) continue;
                else { determinant += 2 * ( -1, * index_number + i ) * Matrix [ * index_number ] [i] * 
                    Determinant ( Matrix_Minor ( Matrix, size, * index_number, i ), size - 1, & index, & index_bool );
                }
            }
        }
        else
        {
            for ( int j = 1; j <= size; j ++ )
            {
                if ( Matrix [j] [ * index_number ] == 0 ) continue;
                else { determinant += 2 * ( -1, j + * index_number ) * Matrix [j] [ * index_number ] *
                    Determinant ( Matrix_Minor ( Matrix, size, j, * index_number ), size - 1, & index, & index_bool );
 
                }
            }
        }
    }
    return ( determinant );
}
 
void Check__Zeros   ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    short int bool_line = 0, bool_columns = 0, max_line = 0, max_columns = 0, line_number = 0, columns_number = 0;
    for ( int i = 1; i <= size; i ++ )
    {
        for ( int j = 1; j <= size; j ++ )
        {
            if ( Matrix [i][j] == 0 )
            {
                bool_line ++;
                if ( j == size - 1 && max_line < bool_line )
                {
                    max_line = bool_line; line_number = i;
                }
            }
            if ( Matrix [j][i] == 0 )
            {
                bool_columns ++;
                if ( j == size - 1 && max_columns < bool_columns )
                {
                    max_columns = bool_columns; columns_number = i;
                }
            }
        }
        bool_line = 0; bool_columns = 0;
    }
    if ( max_line >= max_columns )
    {
        * index_check = true;
        * index_number = line_number;
    }
    else
    {
        * index_check = false;
        * index_number = columns_number;
    }
}
 
double ** & Matrix_Minor ( double ** & Matrix, const short int & size, short int cut_line, short int cut_columns )
{
    short int cut_size = size - 1;
    double ** Matrix_cut = new double * [ cut_size ];
    for ( int i = 1; i <= cut_size; i ++ )
        Matrix_cut [i] = new double [ cut_size ];
    short int n = 0, m = 0;
    for ( int i = 1; i <= size; i ++ )
    {
        if ( i != cut_line )
        {
            for ( int j = 1; j <= size; j ++ )
            {
                if ( j != cut_columns )
                {
                    Matrix_cut [n][m] = Matrix [i][j];
                    m ++;
                }
                else continue;
            }
            n ++; m = 0;
        }
        else continue;
    }
    return ( Matrix_cut );
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
16.07.2013, 10:28
Ответы с готовыми решениями:

Нарушение прав доступа при чтении
Здравствуйте! При отладке выдает данную ошибку: &quot;Вызвано исключение по адресу 0x7795E314 (ntdll.dll) в Lab3-Classes.exe: 0xC0000005:...

Нарушение прав доступа при чтении
#include &lt;iostream&gt; using namespace std; class programm { public: int *mass1 = new int, *mass2 = new int; void...

Нарушение прав доступа при чтении
Имею функцию такого плана: void RenameOldLabels() { USES_CONVERSION; string path, pathAfterRename, pathToDelFile, pathToDelDir,...

15
Неэпический
 Аватар для Croessmah
18144 / 10728 / 2066
Регистрация: 27.09.2012
Сообщений: 27,026
Записей в блоге: 1
16.07.2013, 10:34
C++
1
2
3
    double ** Matrix_A = new double * [ size ];
    for ( int i = 1; i <= size; i ++ )
        Matrix_A [i] = new double [ size ];
Выход за пределы выделенной памяти
1
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52
16.07.2013, 10:52  [ТС]
Цитата Сообщение от Croessmah Посмотреть сообщение
C++
1
2
3
    double ** Matrix_A = new double * [ size ];
    for ( int i = 1; i <= size; i ++ )
        Matrix_A [i] = new double [ size ];
Выход за пределы выделенной памяти
По моему тут правильно т.к. ввод и вывод матрицы производится, а вот определитель не считается
0
Неэпический
 Аватар для Croessmah
18144 / 10728 / 2066
Регистрация: 27.09.2012
Сообщений: 27,026
Записей в блоге: 1
16.07.2013, 10:59
Цитата Сообщение от Helo Посмотреть сообщение
По моему тут правильно
Ну правильно так правильно помочь ничем не могу, тогда
0
16.07.2013, 19:06  [ТС]

Не по теме:

Народ может у кого то есть еще какие либо идеи, варианты, что-нибудь?

0
187 / 172 / 38
Регистрация: 03.08.2012
Сообщений: 596
16.07.2013, 19:38
C++
1
2
3
double ** Matrix_A = new double * [ size ];
    for ( int i = 1; i <= size; i ++ )
        Matrix_A [i] = new double [ size ];
То, что тут выход за пределы дозволенного - это понятно. Вот пример:
C++
1
2
const int size = 5;
int mass[size];
Первый индекс массива не 1 (это в паскале он 1), а 0. Последний не 5, а 4. Индексы идут след. образом: 0 1 2 3 4.
У вас в программе в пытаетесь проделать операцию с ячейками массива, начиная с первой, заканчивая size (включительно). Вот вам и выход за границы массива
0
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52
16.07.2013, 21:33  [ТС]
Цитата Сообщение от Flassie Посмотреть сообщение
C++
1
2
3
double ** Matrix_A = new double * [ size ];
    for ( int i = 1; i <= size; i ++ )
        Matrix_A [i] = new double [ size ];
То, что тут выход за пределы дозволенного - это понятно. Вот пример:
C++
1
2
const int size = 5;
int mass[size];
Первый индекс массива не 1 (это в паскале он 1), а 0. Последний не 5, а 4. Индексы идут след. образом: 0 1 2 3 4.
У вас в программе в пытаетесь проделать операцию с ячейками массива, начиная с первой, заканчивая size (включительно). Вот вам и выход за границы массива
Допустим вы правы, (хотя я не понимаю, что мешает нам задать первый индекс массива = 1, а последний = 5
и будет у нас массив чисел 1 2 3 4 5 включительно). Поменял все условия в программе на эти
C++
1
2
3
4
5
double ** Matrix_A = new double * [ size ];
    for ( int i = 0; i < size; i ++ )
        Matrix_A [i] = new double [ size ];
for ( int i = 0; i < size; i ++ )
        for ( int j = 0; j < size; j ++ )
Проблема осталась.
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
16.07.2013, 21:37
Цитата Сообщение от Helo Посмотреть сообщение
Поменял все условия в программе на эти
Код выложите с исправлениями.
0
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52
16.07.2013, 21:41  [ТС]
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#include "stdafx.h"
 
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include <cmath>
 
short int index = 0;
 
double det = 0;
 
bool index_bool = false;
 
void transponirovanie ( double ** &, const short int & );
void Enter__Check ( double & );
 
void Enter__Array ( double ** &,  const short int & );
void Output_Array ( double ** &,  const short int & );
void Random_Array ( double ** &,  const short int & );
 
void Check__Zeros   ( double ** &, const short int &, short int *, bool * );
double Determinant  ( double ** &, const short int &, short int *, bool * );
double ** & Matrix_Minor ( double ** &, const short int &, short int, short int );
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    setlocale (LC_ALL,"RUSSIAN");
 
 
    short int size;
 
        system ( " cls " );
    
        std::cin >> size;
    double ** Matrix_A = new double * [ size ];
    for ( int i = 0; i < size; i ++ )
        Matrix_A [i] = new double [ size ];
 
    Enter__Array (  Matrix_A, size );
    printf ( "\n%3s", " Матрица А \n\n" );
    transponirovanie (  Matrix_A, size );
    Output_Array (  Matrix_A, size );
    det = Determinant (  Matrix_A, size, & index, & index_bool );
    printf ("\n%3G", det );
    _getch ();
    return 0;
}
 
void Enter__Array ( double  ** & Matrix, const short int & size )
{
    double element;
    printf ( "\n%3s", " Введите элементы массива \n\n" );
    for ( int i = 0; i < size; i ++ )
        for ( int j = 0; j < size; j ++ )
        {
            printf ( " %+20 Matrix [ %d ] [ %d ] = ", i, j );
            Enter__Check (  element );
            Matrix [i][j] = element;
        }
}
 
void Output_Array ( double ** & Matrix, const short int & size )
{
    for ( int i = 0; i < size; i ++ ){
        for ( int j = 0; j < size; j ++ )
            printf ( "%10G\t", Matrix [i][j] );
        printf ( "\n");}
}
/*____________________ Вычисление определителя матрицы _______________________________________*/
 
double Determinant ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    double determinant = 0;
    if ( size == 1 ) return Matrix [0][0];
    else
    {
        Check__Zeros ( Matrix, size, & index, & index_bool );
        if ( * index_check )
        {
 
            for ( int i = 0; i < size; i ++ )
            {
                if ( Matrix [ * index_number ] [i] == 0 ) continue;
                else { determinant += 2 * ( -1, * index_number + i ) * Matrix [ * index_number ] [i] * 
                    Determinant ( Matrix_Minor ( Matrix, size, * index_number, i ), size - 1, & index, & index_bool );
                }
            }
        }
        else
        {
            for ( int j = 0; j < size; j ++ )
            {
                if ( Matrix [j] [ * index_number ] == 0 ) continue;
                else { determinant += 2 * ( -1, j + * index_number ) * Matrix [j] [ * index_number ] *
                    Determinant ( Matrix_Minor ( Matrix, size, j, * index_number ), size - 1, & index, & index_bool );
 
                }
            }
        }
    }
    return ( determinant );
}
 
 
 
/*_______________________________________________ Нахождение нулей ___________________________*/
 
void Check__Zeros   ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    short int bool_line = 0, bool_columns = 0, max_line = 0, max_columns = 0, line_number = 0, columns_number = 0;
    for ( int i = 0; i < size; i ++ )
    {
        for ( int j = 0; j < size; j ++ )
        {
            if ( Matrix [i][j] == 0 )
            {
                bool_line ++;
                if ( j == size - 1 && max_line < bool_line )
                {
                    max_line = bool_line; line_number = i;
                }
            }
            if ( Matrix [j][i] == 0 )
            {
                bool_columns ++;
                if ( j == size - 1 && max_columns < bool_columns )
                {
                    max_columns = bool_columns; columns_number = i;
                }
            }
        }
        bool_line = 0; bool_columns = 0;
    }
    if ( max_line >= max_columns )
    {
        * index_check = true;
        * index_number = line_number;
    }
    else
    {
        * index_check = false;
        * index_number = columns_number;
    }
}
 
double ** & Matrix_Minor ( double ** & Matrix, const short int & size, short int cut_line, short int cut_columns )
{
    short int cut_size = size - 1;
    double ** Matrix_cut = new double * [ cut_size ];
    for ( int i = 0; i < cut_size; i ++ )
        Matrix_cut [i] = new double [ cut_size ];
    short int n = 0, m = 0;
    for ( int i = 0; i < size; i ++ )
    {
        if ( i != cut_line )
        {
            for ( int j = 0; j < size; j ++ )
            {
                if ( j != cut_columns )
                {
                    Matrix_cut [n][m] = Matrix [i][j];
                    m ++;
                }
                else continue;
            }
            n ++; m = 0;
        }
        else continue;
    }
    return ( Matrix_cut );
}
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
16.07.2013, 21:54
Цитата Сообщение от Helo Посмотреть сообщение
хотя я не понимаю, что мешает нам задать первый индекс массива = 1, а последний = 5
Мешает то, что индексы - это смещения в памяти относительно начала массива. Имя массива - это адрес начала массива в памяти. arr[0] - элемент массиваа, который находится по адресу: начало массива + смещением 0, arr[1] - элемент массиваа, который находится по адресу: начало массива + смещением 1 и т.д. Само смещение равно (в байтах) размеру элемента массива (размер типа элемента), применяется арифметика указателей.

Добавлено через 5 минут
А реализации?
C++
1
2
void transponirovanie ( double ** &, const short int & );
void Enter__Check ( double & );
1
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52
16.07.2013, 22:01  [ТС]
А реализации?
C++
1
2
void transponirovanie ( double ** &, const short int & );
void Enter__Check ( double & );
[/QUOTE]
Enter__Check проверяет число на корректность
void Enter__Check ( double & number)
{
std::string symbol;
do
{
std::cin >> number;
if ( std::cin.fail () )
{
std::cin.clear ();
std::cin >> symbol;
printf ( " %s\n ", " Это не число! Повторите ввод данных " ); continue;
}
else break;
}
while ( true );}
Функция транспонирования я еще не законченна, не думаю что проблема в ней
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void swap (double a, double b)
{
    a = a + b;
b = a - b;
a = b - a;
}
void transponirovanie ( double ** & Matrix, const short int & size)
{
    
    for ( int i = 0; i < size; i ++ )
        for ( int j = 0; j < size; j ++ ){
   
            swap(Matrix[i][j], Matrix[i][j]);}
}
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
16.07.2013, 22:04
Цитата Сообщение от Helo Посмотреть сообщение
Функция транспонирования я еще не законченна, не думаю что проблема в ней
А как вы, выложенный код (9 пост), без неё комилируете и запускаете?!
0
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52
16.07.2013, 22:07  [ТС]
Цитата Сообщение от alsav22 Посмотреть сообщение
А как вы, выложенный код, без неё компилируете и запускаете?!
Я имел ввиду, что она не транспонирует заданную матрицу, а программу компилировал без нее
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
16.07.2013, 22:13
Код выложите, который компилируете и пробуете. В компилируемом виде.
0
4 / 4 / 0
Регистрация: 04.07.2013
Сообщений: 52
16.07.2013, 22:22  [ТС]
Вот код в котором возникает ошибка. Мне нужно вычислить определитель матрицы n-го порядка введенной с клавиатуры
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#include "stdafx.h"
 
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include <cmath>
 
short int index = 0;
double det = 0;
bool index_bool = false;
 
void Enter__Check ( double & );
void Enter__Array ( double ** &,  const short int & );
void Output_Array ( double ** &,  const short int & );
void Check__Zeros   ( double ** &, const short int &, short int *, bool * );
double Determinant  ( double ** &, const short int &, short int *, bool * );
double ** & Matrix_Minor ( double ** &, const short int &, short int, short int );
int _tmain(int argc, _TCHAR* argv[])
{
    setlocale (LC_ALL,"RUSSIAN");
    short int size;
        std::cin >> size;
    double ** Matrix_A = new double * [ size ];
    for ( int i = 0; i < size; i ++ )
        Matrix_A [i] = new double [ size ];
    Enter__Array (  Matrix_A, size );
    printf ( "\n%3s", " Матрица А \n\n" );
        Output_Array (  Matrix_A, size );
    det = Determinant (  Matrix_A, size, & index, & index_bool );
    printf ("\n%3G", det );
    _getch ();
    return 0;
}
void Enter__Check ( double & number)
{
    std::string symbol;
    do
    {
        std::cin >> number;
        if ( std::cin.fail () )
        {
            std::cin.clear ();
            std::cin >> symbol;
            printf ( " %s\n ", " Это не число! Повторите ввод данных " ); continue;
        }
        else break;
    }
    while ( true );
}
void Enter__Array ( double  ** & Matrix, const short int & size )
{
    double element;
    printf ( "\n%3s", " Введите элементы массива \n\n" );
    for ( int i = 0; i < size; i ++ )
        for ( int j = 0; j < size; j ++ )
        {
            printf ( " %+20 Matrix [ %d ] [ %d ] = ", i, j );
            Enter__Check (  element );
            Matrix [i][j] = element;
        }
}
void Output_Array ( double ** & Matrix, const short int & size )
{
    for ( int i = 0; i < size; i ++ ){
        for ( int j = 0; j < size; j ++ )
            printf ( "%10G\t", Matrix [i][j] );
        printf ( "\n");}
}
/*_________________ Вычисление определителя матрицы ______________________________*/
 
double Determinant ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    double determinant = 0;
    if ( size == 1 ) return Matrix [0][0];
    else
    {
        Check__Zeros ( Matrix, size, & index, & index_bool );
        if ( * index_check )
        {
 
            for ( int i = 0; i < size; i ++ )
            {
                if ( Matrix [ * index_number ] [i] == 0 ) continue;
                else { determinant += 2 * ( -1, * index_number + i ) * Matrix [ * index_number ] [i] * 
                    Determinant ( Matrix_Minor ( Matrix, size, * index_number, i ), size - 1, & index, & index_bool );
                }
            }
        }
        else
        {
            for ( int j = 0; j < size; j ++ )
            {
                if ( Matrix [j] [ * index_number ] == 0 ) continue;
                else { determinant += 2 * ( -1, j + * index_number ) * Matrix [j] [ * index_number ] *
                    Determinant ( Matrix_Minor ( Matrix, size, j, * index_number ), size - 1, & index, & index_bool );
 
                }
            }
        }
    }
    return ( determinant );
}
/*_______________________________________________ Нахождение нулей ___________________________*/
void Check__Zeros   ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    short int bool_line = 0, bool_columns = 0, max_line = 0, max_columns = 0, line_number = 0, columns_number = 0;
    for ( int i = 0; i < size; i ++ )
    {
        for ( int j = 0; j < size; j ++ )
        {
            if ( Matrix [i][j] == 0 )
            {
                bool_line ++;
                if ( j == size - 1 && max_line < bool_line )
                {
                    max_line = bool_line; line_number = i;
                }
            }
            if ( Matrix [j][i] == 0 )
            {
                bool_columns ++;
                if ( j == size - 1 && max_columns < bool_columns )
                {
                    max_columns = bool_columns; columns_number = i;
                }
            }
        }
        bool_line = 0; bool_columns = 0;
    }
    if ( max_line >= max_columns )
    {
        * index_check = true;
        * index_number = line_number;
    }
    else
    {
        * index_check = false;
        * index_number = columns_number;
    }
}
/*________________________ Миноры ____________________*/
double ** & Matrix_Minor ( double ** & Matrix, const short int & size, short int cut_line, short int cut_columns )
{
    short int cut_size = size - 1;
    double ** Matrix_cut = new double * [ cut_size ];
    for ( int i = 0; i < cut_size; i ++ )
        Matrix_cut [i] = new double [ cut_size ];
    short int n = 0, m = 0;
    for ( int i = 0; i < size; i ++ )
    {
        if ( i != cut_line )
        {
            for ( int j = 0; j < size; j ++ )
            {
                if ( j != cut_columns )
                {
                    Matrix_cut [n][m] = Matrix [i][j];
                    m ++;
                }
                else continue;
            }
            n ++; m = 0;
        }
        else continue;
    }
    return ( Matrix_cut );
}
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
16.07.2013, 22:58
Не знаю, правильно ли считает, но прежней ошибки нет:
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include <cmath>
 
short int index = 0;
double det = 0;
bool index_bool = false;
 
void Enter__Check ( double & );
void Enter__Array ( double ** &,  const short int & );
void Output_Array ( double ** &,  const short int & );
void Check__Zeros   ( double ** &, const short int &, short int *, bool * );
double Determinant  ( double ** , const short int &, short int *, bool * );
double **  Matrix_Minor ( double ** &, const short int &, short int, short int );
 
int main()
{
    setlocale (LC_ALL,"RUSSIAN");
    
    short int size;
    std::cin >> size;
    
    double ** Matrix_A = new double * [ size ];
    for ( int i = 0; i < size; i ++ )
        Matrix_A [i] = new double [ size ];
   
    Enter__Array (  Matrix_A, size );
    printf ( "\n%3s", " Матрица А \n\n" );
        Output_Array (  Matrix_A, size );
    det = Determinant (  Matrix_A, size, & index, & index_bool );
    printf ("\n%3G", det );
    _getch ();
    return 0;
}
void Enter__Check ( double & number)
{
    std::string symbol;
    do
    {
        std::cin >> number;
        if ( std::cin.fail () )
        {
            std::cin.clear ();
            std::cin >> symbol;
            printf ( " %s\n ", " Это не число! Повторите ввод данных " ); continue;
        }
        else break;
    }
    while ( true );
}
void Enter__Array ( double  ** & Matrix, const short int & size )
{
    double element;
    printf ( "\n%3s", " Введите элементы массива \n\n" );
    for ( int i = 0; i < size; i ++ )
        for ( int j = 0; j < size; j ++ )
        {
            printf ( " %+20 Matrix [ %d ] [ %d ] = ", i, j );
            Enter__Check (  element );
            Matrix [i][j] = element;
        }
}
void Output_Array ( double ** & Matrix, const short int & size )
{
    for ( int i = 0; i < size; i ++ ){
        for ( int j = 0; j < size; j ++ )
            printf ( "%10G\t", Matrix [i][j] );
        printf ( "\n");}
}
/*_________________ Вычисление определителя матрицы ______________________________*/
 
double Determinant ( double ** Matrix, const short int & size, short int * index_number, bool * index_check )
{
    double determinant = 0;
    if ( size == 1 ) return Matrix [0][0];
    else
    {
        Check__Zeros ( Matrix, size, & index, & index_bool );
        if ( * index_check )
        {
 
            for ( int i = 0; i < size; i ++ )
            {
                if ( Matrix [ * index_number ] [i] == 0 ) continue;
                else { determinant += 2 * ( -1, * index_number + i ) * Matrix [ * index_number ] [i] * 
                    Determinant ( Matrix_Minor ( Matrix, size, * index_number, i ), size - 1, & index, & index_bool );
                }
            }
        }
        else
        {
            for ( int j = 0; j < size; j ++ )
            {
                if ( Matrix [j] [ * index_number ] == 0 ) continue;
                else { determinant += 2 * ( -1, j + * index_number ) * Matrix [j] [ * index_number ] *
                    Determinant ( Matrix_Minor ( Matrix, size, j, * index_number ), size - 1, & index, & index_bool );
 
                }
            }
        }
    }
    return ( determinant );
}
/*_______________________________________________ Нахождение нулей ___________________________*/
void Check__Zeros   ( double ** & Matrix, const short int & size, short int * index_number, bool * index_check )
{
    short int bool_line = 0, bool_columns = 0, max_line = 0, max_columns = 0, line_number = 0, columns_number = 0;
    for ( int i = 0; i < size; i ++ )
    {
        for ( int j = 0; j < size; j ++ )
        {
            if ( Matrix [i][j] == 0 )
            {
                bool_line ++;
                if ( j == size - 1 && max_line < bool_line )
                {
                    max_line = bool_line; line_number = i;
                }
            }
            if ( Matrix [j][i] == 0 )
            {
                bool_columns ++;
                if ( j == size - 1 && max_columns < bool_columns )
                {
                    max_columns = bool_columns; columns_number = i;
                }
            }
        }
        bool_line = 0; bool_columns = 0;
    }
    if ( max_line >= max_columns )
    {
        * index_check = true;
        * index_number = line_number;
    }
    else
    {
        * index_check = false;
        * index_number = columns_number;
    }
}
/*________________________ Миноры ____________________*/
double ** Matrix_Minor ( double ** & Matrix, const short int & size, short int cut_line, short int cut_columns )
{
    short int cut_size = size - 1;
    double ** Matrix_cut = new double * [ cut_size ];
    for ( int i = 0; i < cut_size; i ++ )
        Matrix_cut [i] = new double [ cut_size ];
    short int n = 0, m = 0;
    for ( int i = 0; i < size; i ++ )
    {
        if ( i != cut_line )
        {
            for ( int j = 0; j < size; j ++ )
            {
                if ( j != cut_columns )
                {
                    Matrix_cut [n][m] = Matrix [i][j];
                    m ++;
                }
                else continue;
            }
            n ++; m = 0;
        }
        else continue;
    }
    return ( Matrix_cut );
}
Добавлено через 4 минуты
По-моему, здесь ссылки на указатели на указатели не нужны. Достаточно просто указателей на указатели. Если убрать, то работает точно так же.
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
16.07.2013, 22:58
Помогаю со студенческими работами здесь

Нарушение прав доступа при чтении
Собственно код программы: #include &quot;stdio.h&quot; #include &quot;conio.h&quot; #include &quot;math.h&quot; #include &quot;string.h&quot; #include...

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

Нарушение прав доступа при чтении
При некоторых случаях выскакивает такая ошибка: Если изменить код на такой: то ошибка не появляется. Как узнать в чём причина?

Нарушение прав доступа при чтении
Здравствуйте! На строке catalog-&gt;push_back(*record); Выдает ошибку: Первый этап обработки исключения в &quot;0x00173589&quot; в...

Нарушение прав доступа при чтении
Добрый день при выполнении программы выходит ошибка: Необработанное исключение в &quot;0x00ce4893&quot; в &quot;Diskret.exe&quot;:...


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

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
Новые блоги и статьи
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru