Модераторы: Partizan, gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> В каджом столбце массива А поменять местами первый 
:(
    Опции темы
carmen03
  Дата 31.5.2011, 14:47 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 1
Регистрация: 31.5.2011

Репутация: нет
Всего: нет



Дан двумерный числовой массив А [n, m] .
 Составить программу, реализующую следующие действия:

 1. В каджом столбце массива А поменять местами первый отрицательный элемент с последним элементом столбца.
 2. Выделить в одномерный массив в положительные элементы массива А из тех столбцов ,в которых есть отрицательные элемены. 
 3. Определить номера столбцов массива А, в которых сумма элементов больше значения первого элемента массива А.

 помогите очень - очень нужно ((

пожалуста..

Это сообщение отредактировал(а) carmen03 - 31.5.2011, 14:50
PM MAIL   Вверх
Gluttton
Дата 5.6.2011, 12:16 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Начинающий
***


Профиль
Группа: Завсегдатай
Сообщений: 1170
Регистрация: 28.8.2008
Где: Феодосия

Репутация: 2
Всего: 54



carmen03, не ручаюсь за правильность и оптимальсность, но примерно так:
Код

using System;

namespace Gluttton.ArrayTasks
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            int [][] array = new int [][]{
                new [] {-1, 6,  6,  7,  5,  8},
                new [] {-4, 6,  7,  7, -2,  9},
                new [] {3,  7,  8,  7, -8,  9},
                new [] {1,  7,  9,  7, -7,  9}
            };
            
            Console.Write ("Program start.\n\n");
            
            Console.Write ("======================================\n");            
            Console.Write ("Content of the array:\n");
            for (int i = 0; i < array.Length; i++) {
                for (int j = 0; j < array[i].Length; j++) {
                    Console.Write ("{0}\t", array[i][j]);
                }
                Console.Write ("\n");
            }
            Console.Write ("\n");
            
            Console.Write ("======================================\n");
            Console.Write ("Replace negative elements with last element.\n");
            Console.Write ("Start.\n");
            Console.Write ("Copy array start.\n");
            int [][] replaceArray = new int [array.Length][];
            for (int i = 0; i < replaceArray.Length; i++) {
                replaceArray [i] = new int [array[i].Length];
                    for (int j = 0; j < replaceArray [i].Length; j++) {
                        replaceArray [i][j] = array [i][j];
                }
            }
            Console.Write ("Copy array finish.\n");
            Console.Write ("Replace negative elements start.\n");
            for (int j = 0; j < replaceArray[0].Length; j++) {
                for (int i = 0; i < replaceArray.Length; i++) {
                    if (replaceArray [i][j] < 0) {
                        int temporal = replaceArray [replaceArray.Length - 1][j];
                        replaceArray [replaceArray.Length - 1][j] = replaceArray [i][j];
                        replaceArray [i][j] = temporal;
                        break;
                    }
                }
            }
            Console.Write ("Replace negative elements finish.\n");
            Console.Write ("Content of the replaced array:\n");
            for (int i = 0; i < replaceArray.Length; i++) {
                for (int j = 0; j < replaceArray[i].Length; j++) {
                    Console.Write ("{0}\t", replaceArray[i][j]);
                }
                Console.Write ("\n");
            }
            Console.Write ("\n");            
            Console.Write ("Replace negative elements finish.\n");
            Console.Write ("Finish.\n");
            
            Console.Write ("======================================\n");
            Console.Write ("Create positive array.\n");
            Console.Write ("Start.\n");
            Console.Write ("Copy positive elements start.\n");
            object [] positiveArray = new object [array.Length * array[0].Length];
            int positiveArrayIndex = 0;
            for (int j = 0; j < array[0].Length; j++) {
                for (int i = 0; i < array.Length; i++) {
                    if (array [i][j] < 0) {
                        for (int k = 0; k < array.Length; k++) {
                            if (array [k][j] > 0) {
                                positiveArray [positiveArrayIndex] = array [k][j];
                                positiveArrayIndex++;
                            }
                        }
                        j++;
                    }
                }
            }
            Console.Write ("Copy positive elements finish.\n");
            Console.Write ("Content of the positive elements array:\n");
            for (int i = 0; i < positiveArray.Length; i++) {
                Console.Write ("{0}\t", positiveArray[i]);
            }
            Console.Write ("\n");                                                            
            Console.Write ("Finish.\n");
            
            Console.Write ("======================================\n");
            Console.Write ("Find columns with sum larger than first element.\n");
            Console.Write ("Start.\n");
            for (int j = 0; j < array[0].Length; j++) {
                int sum = 0;
                for (int i = 0; i < array.Length; i++) {
                    sum += array [i][j];
                }
                if (sum > array [0][j]) {
                    Console.Write ("{0}\t", j);
                }
            }
            Console.Write ("\n");
            Console.Write ("* - number of columns start from 0.\n");
            Console.Write ("Finish.\n");
            
            Console.Write ("Program finish.\n");
        }
    }
}


Результат работы программы:
Цитата

Program start.
======================================
Content of the array:
-1    6    6    7    5    8    
-4    6    7    7    -2    9    
3    7    8    7    -8    9    
1    7    9    7    -7    9    
======================================
Replace negative elements with last element.
Start.
Copy array start.
Copy array finish.
Replace start.
Replace finish.
Content of the replaced array:
1    6    6    7    5    8    
-4    6    7    7    -7    9    
3    7    8    7    -8    9    
-1    7    9    7    -2    9    
Replace negative elements finish.
Finish.
======================================
Create positive array.
Start.
Copy positive elements start.
Copy positive elements finish.
Content of the positive elements array:
3    1    5                      
Finish.
======================================
Find columns with sum larger than first element.
Start.
1    2    3    5    
* - numbers of columns start from 0.
Finish.
Program finish.


Кроме этого необходимо:
- проверить орфографию выводимых сообщений;
- добавить проверку массива на "квадратность" - в противном случае на зубчатых массивах программа будет "падать";
- расставить, где это необходимо обработки исключений (блоки try catch), кстати, тогда предыдущий пункт можно опустить.


--------------------
Слава Україні!
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Общие вопросы по .NET и C# | Следующая тема »


 




[ Время генерации скрипта: 0.0785 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.